185.3 + 12.37 = 197.67000000000002? [duplicate]
This page has a simple alert:
alert(185.3 + 12.37);
To me, that should equal 197.67
However, in the browsers I've tested (Chrome/Safari on OSX, FF on Win7) the answer is:
197.67000000000002
Why is that? Is this just a known bug or is there more to JavaScript addition than I realize?
javascript uses the double
datatype, which can't, due to restricted binary places, express all decimal numbers accurately (not all numbers can be expressed with finite binary places). You can read more at wikipedia.
You should read this:
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html
It's not a bug; it's just a well-known fact of floating point numbers for every language.
In binary, this is the infinitely repeating binary fraction 11000101.10(10101110000101000111)
- which cannot be represented in a finite number of bits, so it is rounded to an approximation.
精彩评论