0

Possible Duplicate:
Is JavaScript's Math broken?

Any ideas as to why:

(872.23 + 2315.66 + 4361.16) == 7549.05

return false in a Javascript console (e.g. Chrome Developer console)?

If I try it with my calculator, the left side does exact 7549.05... However, Javascript displays it as 7549.049999999999. I could "fix" it or round it, or... but WHY should I be doing that for simple additions?

Thanks

Community
  • 1
  • 1
Ayyoudy
  • 3,641
  • 11
  • 47
  • 65

4 Answers4

1

That is not Javascript adding extra precision, that is your computer's floating-point representation not being able to accurately represent your number. Get around it by using rational numbers or fixed-point (instead of floating-point) arithmetic.

Eric Finn
  • 8,629
  • 3
  • 33
  • 42
1

By using decimals, you are using floating point numbers. You would have to know a bit about how floating point is represented in binary form, and how binary floating point addition works to understand why adding floating point numbers does not always resolve to what you want.

Here is a quick google result that you might want to glance at: The Complete Javascript Number Reference

Also, if you want to learn how floating point is represented in binary look at IEEE floating point on Wikipedia.

Your best bet in this case would be to round.

twmb
  • 1,710
  • 1
  • 20
  • 18
1

This is because of how floats are represented in the hardware (32 bits, probably, but it's the same in any number of bits). Basically the issue is you can't represent something like "7549.05" exactly (more on this issue in wikipedia).

So, for practical uses, if the numbers are currency, a good option is multiplying by 100 so they are always integers, and operating with ints (which will give good results when adding, substracting or multiplying).

cambraca
  • 27,014
  • 16
  • 68
  • 99
1

Marco Mariani answered a similar question a short time ago:

What Every Computer Scientist Should Know About Floating Point Arithmetic

and the shorter, more to the point:

http://floating-point-gui.de/

Community
  • 1
  • 1
bjelli
  • 9,752
  • 4
  • 35
  • 50
  • Thank you. I had already tagged my question with the keyword "float" when I posted it because I had suspected that this is the reason. It just seemed like a JS issue at first because I was doing the same thing with SQL and it was giving me what I wanted. I guess it is implementation dependent. – Ayyoudy Jun 26 '12 at 19:41