Why 0.03%0.01 = 0.0099999 and not 0, and how to fix it?

Why 0.03%0.01 = 0.0099999 and not 0, and how to fix it?
0.0 0


Dear friends,

The division 0.03%0.01 should be 0, however we get 0.009999999999999998 . Do you know any workaround?



It’s a floating point rounding error. Floating point is an efficient and flexible way to store arbitrarily large or small numbers, but unfortunately it comes at the cost of some accuracy. It’s also, infuriatingly, the only numerical type that JavaScript natively supports.

For many purposes (such as currency), multiplying by 10 or 100 and then dividing by that again when outputting the answer will give you the precision you need.


Thanks for your answer. I know that, but I thought that probably there is an elegant solution of this …


Well, it depends what your definition of “elegant” is. If you don’t mind using a library, https://github.com/MikeMcl/bignumber.js/ usually comes highly recommended.

If you’re interested in the theory, here’s some further reading: https://medium.com/dailyjs/javascripts-number-type-8d59199db1b6


you can use toFixed or toPrecision to get around the rounding.


That’s a good idea in many cases, but won’t work in the OP’s case:

(0.3 % 0.1).toFixed(1); //evaluates to "0.1", but should be "0.0"


Thanks! The first link is useful …