Reputation:
I'm trying to increase by one this number: 9223372036854775808
:
var number = 9223372036854775808;
var plusOne = number + 1;
This should yield 9223372036854775809, but it instead yields 9223372036854776000.
Why? More important, how can I fix this?
Upvotes: 4
Views: 192
Reputation: 11171
The largest representable number in JavaScript is (2^53) - 1
, or, written out, 9007199254740991
. The number you have, 9223372036854775808
, is more than 1024 times that quantity.
If you want to work with numbers larger than the one above, you should use a big integer library. JavaScript does not have one built in, however, so you'll need to grab it yourself. Personally, I use big-integer when I'm working on things that deal with really large numbers, e.g., Project Euler.
Upvotes: 6
Reputation: 7634
This is to do with JavaScript storing numbers internally as (double precision) floating point. As you go up the scale of floating point numbers, the numbers get more and more sparse until the point where you get incorrect results, because the next representable number is more that 1 away (As in your example). To properly handle large numbers, you will need to use a proper large number library such as javascript-bignum. If you only need integers, you can use BigInteger.js
Upvotes: 4