-3
console.log((57 / 100) * 100);

When I did this math in Javascript it always return 56.99999999. Why its not 57.00000?

Subin Jacob
  • 4,692
  • 10
  • 37
  • 69
  • 4
    This is a problem not limited to javascript but the accuracy of floating point arithmetic in general, http://floating-point-gui.de/. – Xotic750 May 01 '13 at 11:10
  • follow this http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken – Trikaldarshiii May 01 '13 at 12:52

2 Answers2

4

That has to do with the way JavaScript handles floating point numbers. Check out this topic: How to deal with floating point number precision in JavaScript?

Community
  • 1
  • 1
Jochen van Wylick
  • 5,303
  • 4
  • 42
  • 64
2

In order to get an exact answer, you will need to work in integers, or use a decimal library. There are some decimal libraries for Javascript which compute the values using integers, then convert the values back to decimal. For example, there is the BigNumber library for Javascript.

The reason for this is that the section (57 / 100) returns a Float, or floating point number in Javascript. JavaScript uses 64-bit floating point numbers, which on most systems, gives 53 bits of precision to represent the mantissa, or numeric part of the float (the 3.2 in 3.2e4). Most systems use the IEEE-754 floating point standard, which allows for any error of the floating point operations as long as it's less than one unit in the last place (which in the case of IEEE-754 64-bit is the 54th bit). Therefore, all floats are cut off, rounded and/or truncated, which is why the result returns a fractional number.

For more information on why this happens, you can also see: Is floating point math broken?

Community
  • 1
  • 1
KernelPanik
  • 8,169
  • 1
  • 16
  • 14