2

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?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
DA.
  • 39,848
  • 49
  • 150
  • 213

3 Answers3

8

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.

Femaref
  • 60,705
  • 7
  • 138
  • 176
  • Well, it looks like this question has been asked before. ;O) Thanks for the answer! – DA. Apr 11 '11 at 01:28
3

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
2

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.

Random832
  • 37,415
  • 3
  • 44
  • 63