The Simple and Not Boring Guide to Rounding Accurately in Javascript
There is a big problem in javascript. You might have heard software engineers joke that Javascript is bad at math, and if you’ve ever tried to have Javascript do some math for you, for example
Or perhaps you’ve tried some rounding, and gotten an unexpected result such as
There are a number of posts explaining the details about why this is happening, so I’m just going to focus on fixing it. Because it’s a lengthy explanation, and this post is just about fixing it.
A common solution is to use the method toFixed()
in order to correct this mistake. And I can just hear you asking, “Well if it works, why not?”
Well there are a few reasons I wouldn’t recommend it, one of them being that toFixed
is converting your float to a string, which means you have to run parseInt to convert the type back, and running parseInt leaves it prone to new inaccuracies. Doing all those conversions can all a lot of unnecessary time to your function (even these built in functions have a time cost.)
But my favorite reason to not use toFixed
is it’s still not accurate.
So don’t use it to try to fix rounding errors.
On to the solution! What’s a poor Software Engineer who really just needs to round 1.005 to do!?
Well the answer looks scary, and sounds scary, but it isn’t as complicated as you’d imagine. We’re going to use exponential notation.
Again. There are great articles breaking down exponential notation. I’m just going to show you how to use it! So no need to fear!
So instead of (1.005 * 100) / 100
we’re going to be doing (e3 and e-3 if you want it rounding to the thousands place, e4 and e-4 for ten thousands, etc. This is e-notation in javascript).
And there we have it. It’s as simple as that. Enjoy your newfound powers of accurate rounding in Javascript, all without converting your data type.