-1

When I try 0.14 * 100 in browser console (result is same in all browsers), I get 14.000000000000002 as a result. If I, however, try 0.14 * 1000, it correctly returns 140.

If it returned approximate results in both cases, I'd just assume that 0.14 cannot be exactly represented in binary, but this doesn't seem to be the case.

EDIT: no, it is not duplicate of Is floating point math broken? - they use 0.1 + 0.2, which evaluates to imprecise number. Meanwhile, 0.14 is completely precise, the problem only occurs when multiplying it by 10 / 100, but it works with 1000.

EDIT: sorry, it's not precise, but the point stands - why does it return whole number when multiplied by 1000?

Community
  • 1
  • 1
user2486570
  • 902
  • 8
  • 14
  • Try this http://stackoverflow.com/questions/5037839/avoiding-problems-with-javascripts-weird-decimal-calculations – undefined Apr 30 '17 at 15:45
  • 1
    Note that `0.14 = 2582544170319337226.24 * 2^-64`. Can you give us the binary representation of `0.14`? Hint: if the binary representation would be shorter than 64 letters, multiplying by 2^64 would yield an integer. – phihag Apr 30 '17 at 15:50

1 Answers1

-1

0.14 cannot be represented precisely as a javascript float, so when you multiply by 100, the rounding error introduced by converting the string "0.14" to a float carries through to the result.

faffaffaff
  • 3,429
  • 16
  • 27