Welcome to this mini series of me trying to solve a simple math problem with Javascript. I apologize in advance to everyone more capable in both math and javascript.
- Divide a number by 100 and limit the result's amount of decimals to 5 tops.
- Expected outcome: 49.95 becomes 0.4995 and 9.95 becomes 0.0995.
That's easy, you might think.
Dividing by 100 is just "moving the decimal place" two steps forward, so 49.95 becomes 0.4995 - right?
const attempt1 = parseFloat(49.95 / 100);
// attempt1 => 0.49950000000000006
Well, that's weird and unexpected.
Okay, off to StackOverflow. How does the geniuses solve this one?
const attempt2 = Math.round(parseFloat(49.95 / 100) * 100) / 100;
// attempt2 = 0.5
Wrong again.
Maybe we can do some nice string slicing and hack it out...
const attempt3 = parseFloat(parseFloat(49.95 / 100)
.toString()
.split(".")
.map(x => x.slice(0,5))
.reduce((a,b) => a+'.'+b));
// const attempt3 = 0.49950
Boooya!
But after playing around with some other number combinations it gives dodgy results; e.g. 9.95 becomes 0.0994 which should be 0.995. Too sketchy to make it to production.
Okay, let's just try to keep it simple... let's combine the logic from above and use basic math:
const attempt4 = (parseFloat(49.95) * 100) / 10000;
// attempt4 = 0.4995
BINGO!
Now, let's just make sure it also works with the dodgy 9.95...
aaaaannnd...
// => 0.09949999999999999
DAMN IT! WTF is this? I don't even!! Holy s*it, man! F**k!
I'm calm. I'm calm. No need to panic. Math has failed you. Or Javascript certainly has. No need to crawl into fetus position and doubt your life choices.
There must be a way out of this...
Let's go back to string manipulation. Maybe we can use the toFixed-function and repurpose the string as a float without the weirdly long decimals?
const attempt5 = parseFloat(parseFloat(49.95 / 100).toFixed(5));
// attempt5 = 0.4995
Oh jolly good! 🤓
And even the dodgy 9.95 returns 0.0995. Happy days! 🚀
If you liked this walk-through of me trying to solve a basic math and javascript problem, please drop a comment below.
I would love to hear your thoughts on this, general feedback or maybe even a smarter, shorter, quicker and safer solution to this problem?
Cheers.
/ Anders