views:

92

answers:

2

Let's see this example.

<html>
 <body onload="alert((0.1234*300));alert((0.00005*300))"/>
</html>

Why the results are not as should be 37.02 and 0.015 but 37.019999999999996 and 0.015000000000000001 ?

Ps: 0.00005*300 make error while 0.0005*30 and 0.005*3 are ok.

+5  A: 

All numbers in JavaScript are represented in binary as IEEE-754 Doubles, which provides an accuracy to about 14 or 15 significant digits. Because they are floating point numbers, they do not always exactly represent real numbers (Source):

console.log(0.1234 * 300);    // 37.019999999999996
console.log(0.00005 * 300);   // 0.015000000000000001     

You will also be interested in checking out the following post:

Daniel Vassallo
+8  A: 

You need to have a good read of What Every Computer Scientist Should Know About Floating-Point Arithmetic

Russell Dias
\*sigh\* Sometimes I think the only reason why there never is any real progress is that the old and experienced die while the young have to be taught all the same stuff again and again. :-P
Tomalak
Yep, but something I want to figure out is when these will happen or Should I use round() everywhere? because only 0.00005*300 make error while 0.0005*30 is ok, 0.005*3 is ok.
pinichi
Yep. The calculation, most of the time has to be rounded to get a representation. If I may ask, do you really need this amount of precision?
Russell Dias
You have a couple of options.. I would suggest you either `Math.round` as you suggested yourself, or alternatively, you can multiply it by 100, 1000, etcetera - the amount of precision you need. Do the calculations in the hundreds or thousands and than divide it by the number you used earlier.
Russell Dias