0

I have been using this for sometime now before I noticed that is not reliable

Math.floor(16.65*100) / 100 = 16.64

Why does this happen? Any reliable alternative for rounding down safely in JS?

uautkarsh
  • 492
  • 3
  • 9
pokken
  • 327
  • 1
  • 15
  • 1
    `Math.floor(16.65*100) * 100 ` is return 166400. Any typo? – sinbar Oct 16 '18 at 08:08
  • Can you reread your question? The answer should be 166500. Did you accidentally multiply instead of divide in your example above? – spender Oct 16 '18 at 08:09
  • I've said this before, and I'll say it again - in floating point math rounding should only be done as the _final_ step, and only for _presentation_ of the value. This is why `Number.prototype.toFixed` returns a _string_. – Alnitak Oct 16 '18 at 08:10
  • Cannot add this as the answer as its marked as duplicate, but to answer the second part of the question about reliable alternatives: I have had good experience with https://github.com/MikeMcl/decimal.js library for floating point operations. They have a light version of that library as well: https://github.com/MikeMcl/decimal.js-light – uautkarsh Oct 16 '18 at 08:26

1 Answers1

0

It's because 16.65 * 100 is calculated to 1664.9999999999998

yunzen
  • 32,854
  • 11
  • 73
  • 106
  • Great answer. Here's a jsFiddle illustrating it: https://jsfiddle.net/dajskz4m/2/ –  Oct 16 '18 at 09:00