0

I have a number n which is 16 digits long (1111111111111111). When I add another 1 to this number (making it 11111111111111111, 17 digits long) it is displayed as 11111111111111112.

This is understandable because it is larger than Number.MAX_SAFE_INTEGER, however if I add a 0 instead (making it 11111111111111110, still 17 digits long), the number is displayed correctly as 11111111111111110.

let a = 11111111111111111;
let b = 11111111111111110;

console.log(a, b); // 11111111111111112 11111111111111110

The behaviour above occurs with any final digit, apart from 0. What is the reason for this difference in behaviour?


I have looked at "Large numbers erroneously rounded in Javascript", but that doesn't explain why it is rounded when a non-zero number is added, and not when a zero is added.

Community
  • 1
  • 1
James Monger
  • 10,181
  • 7
  • 62
  • 98
  • looks like a integer rounding problem in javascript – mtizziani Nov 16 '16 at 11:37
  • Downvoter: Why the downvote? This is a well-explained question for which I cannot find a duplicate. – James Monger Nov 16 '16 at 11:41
  • 1
    Possible duplicate of [Large numbers erroneously rounded in Javascript](http://stackoverflow.com/questions/1379934/large-numbers-erroneously-rounded-in-javascript) – Sebastian Simon Nov 16 '16 at 11:52
  • @Xufox I've edited my question to explain why it's not a duplicate. – James Monger Nov 16 '16 at 11:54
  • Not sure what’s not understandable about this behavior. Try appending a `2`. It’s not rounded to a different number either. As the answers in the duplicate target state, it’s _rounded_ if a number can’t be represented otherwise. Even numbers _can_ be represented at this size. Yet larger numbers can only represent every fourth, then every eighth number etc. It’s not about zero vs. non-zero. – Sebastian Simon Nov 16 '16 at 11:58
  • Thanks @Xufox that makes sense. Would you like to post it as an answer so I can accept it? – James Monger Nov 16 '16 at 12:01
  • 1
    @JamesMonger I’d argue, the answers from the other question explain that sufficiently already, so no. – Sebastian Simon Nov 16 '16 at 12:04

1 Answers1

0

This is because in Javascript, numbers are stored as double precision floating point numbers. Large integers exceed the precision range of doubles, so they become inaccurate.

hashseed
  • 11
  • 1