Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Possible Duplicate:
Is JavaScript’s Math broken?

Why does JS screw up this simple math?

console.log(.1 + .2)  // 0.3000000000000004  console.log(.3 + .6)  // 0.8999999999999999

The first example is greater than the correct result, while the second is less. ???!! How do you fix this? Do you have to always convert decimals into integers before performing operations? Do I only have to worry about adding (* and / don't appear to have the same problem in my tests)?

I've looked in a lot of places for answers. Some tutorials (like shopping cart forms) pretend the problem doesn't exist and just add values together. Gurus provide complex routines for various math functions or mention JS "does a poor job" in passing, but I have yet to see an explanation.

like image 493
Greg Perham Avatar asked Aug 09 '10 10:08

Greg Perham


People also ask

How do I get 2 decimal places in JavaScript?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

How do you sum decimals in JavaScript?

To add two decimal numbers in JavaScript use the toFixed() function to convert it to a string with some decimal places shaved off, and then convert it back to a number.

How many decimals can JavaScript handle?

The maximum number of decimals is 17.

What is double precision in JavaScript?

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding.


1 Answers

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.

like image 147
mb14 Avatar answered Sep 24 '22 23:09

mb14