0

Possible Duplicate:
Is JavaScript's Math broken?

It returns

5.074999999999999

Why is that?

And what other numbers will give a similar demonstration of this?

Community
  • 1
  • 1
Eran Medan
  • 44,555
  • 61
  • 184
  • 276

3 Answers3

6

Essential reading on floating point arithmetic.

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

In a nutshell:

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

Matthew Vines
  • 27,253
  • 7
  • 76
  • 97
4

Well, the classic example is:

0.1 + 0.2 = 0.30000000000000004

IEEE 754 double-precision floating-point numbers (which is what JavaScript uses) are very very good, but they're not perfect. They offer a fast way of doing mostly-correct, but not perfect, computation on floating-point numbers. All number systems have such compromises (try to accurately represent 1 / 3 — or PI, for that matter — in a limited number of decimal digits, for instance).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

It’s normal – There’s a thing called precision while working with floating point numbers. It’s present in most of the modern languages. See here: http://www.mredkj.com/javascript/nfbasic2.html for more information.

In this line of thought – you cannot compare floating point numbers without using EPS (epsilon value). If you need more information – feel free to contact me again.