Search code examples
javascriptfloating-point-precision

How to obtain only the integer part of a long floating precision number with JS?


I know there's

  • Math.floor
  • parseInt

But about this case:

Math.floor(1.99999999999999999999999999)

returning 2, how could I obtain only its integer part, equals to 1?


Solution

  • 1.99999999999999999999999999 is not the actual value of the number. It has a value of 2 after the literal is parsed because this is 'as best' as JavaScript can represent such a value.

    JavaScript numbers are IEEE-754 binary64 or "double precision" which allow for 15 to 17 significant [decimal] digits of precision - the literal shown requires 27 significant digits which results in information loss.

    Test: 1.99999999999999999999999999 === 2 (which results in true).

    Here is another answer of mine that describes the issue; the finite relative precision is the problem.