-1

Information

Number.MAX_SAFE_INTEGER = 9007199254740991 link

Issue

1000000000000 === 999999999999.999999  // Gives output true
1000000000000 === 999999999999.99999   // Gives output true
1000000000000 === 999999999999.9999    // Gives output false

Any clue why this is happening?

Community
  • 1
  • 1
user1496463
  • 410
  • 3
  • 14
  • In short: never expect any particular floating point number to be exactly equal to any other number. Yes, you can probably figure out what exactly is happening here if you dig into it, but why bother when you're violating a fundamental principle of working with inaccurate floats to begin with? – deceze Aug 21 '18 at 11:47
  • I can understand why floating point operations (like addition) fails. But why should something like equality fail? `(0.1 + 0.2) === 0.3 // gives false` makes sense. But not this. – user1496463 Aug 21 '18 at 12:10
  • If a value simply cannot be expressed precisely in float, it snaps to another value close by that *can* be expressed. Here the first two numbers round up to `1000000000000`, simply by the mere fact of trying to express them. – deceze Aug 21 '18 at 12:11
  • 1
    When the decimal numerals are converted to a JavaScript `Number`, the result is the number represented by the decimal numeral rounded to the nearest value representable in floating-point. For “999999999999.99999” and “999999999999.99999”, the nearest representable value is 1000000000000. So `999999999999.99999` in source code becomes 1000000000000, and then comparison for equality is comparing 1000000000000 to 1000000000000, so it returns true. In the case of “999999999999.9999”, the nearest value is 999999999999.9998779296875, so the comparison returns false. – Eric Postpischil Aug 21 '18 at 13:59

1 Answers1

1

Because floats have low precision.

http://en.wikipedia.org/wiki/Floating-point

Jonas B
  • 2,351
  • 2
  • 18
  • 26
  • A 64-bit floating-point number has more precision than a 32-bit integer. It is not the degree of precision *per se* that causes floating-point rounding issues but rather than nature of how they behave compared to what people expect. – Eric Postpischil Aug 21 '18 at 13:55
  • well a decimal is base 10 while computers work in base 2 perhaps i formulated myself incorrectly when I used the term precision. – Jonas B Aug 21 '18 at 14:09