[JS]Rounding error?

Associate
Joined
21 May 2003
Posts
1,365
I've been banging my head against this for an hour or two now.

I'm trying to subtract 77.495 from 100, but I can't get the correct answer.

It keeps giving 22.504999 rather than 22.505.

I've tried parseFloat(), Number(), all still give the incorrect answer...

try it yourself:
Code:
alert(100.0000 - 77.495);

any ideas?
 
Ok well even if I do the calculation in PHP and then pass the number to Javascript, it still causes the precision error.

I know this is inherently due to the way computers store fractions but I would've thought JS would have similar precision to most other languages.

I've found a way to work around it by using toFixed(6) to round it to the nearest decimal place but it shouldn't need rounding in the first place!
 
Back
Top Bottom