Why does adding two decimals in Javascript produce a wrong result? [duplicate]

It’s not a JS problem but a more general computer one. Floating number can’t store properly all decimal numbers, because they store stuff in binary
For example:

0.5 is store as b0.1 
but 0.1 = 1/10 so it's 1/16 + (1/10-1/16) = 1/16 + 0.0375
0.0375 = 1/32 + (0.0375-1/32) = 1/32 + 00625 ... etc

so in binary 0.1 is 0.00011... 

but that’s endless.
Except the computer has to stop at some point. So if in our example we stop at 0.00011 we have 0.09375 instead of 0.1.

Anyway the point is, that doesn’t depend on the language but on the computer. What depends on the language is how you display numbers. Usually, the language rounds numbers to an acceptable representation. Apparently JS doesn’t.

So what you have to do (the number in memory is accurate enough) is just to tell somehow to JS to round “nicely” number when converting them to text.

You may try the sprintf function which give you a fine control of how to display a number.

Leave a Comment