4

I thought the max integer value for javascript was 2^53, but when I do the following:

 parseInt(Math.pow(2, 53)) + 10

I correctly get 9007199254741002

 (= 9007199254740992 + 10)

Why is that? I want to use a bigint.js library only if the number is greater than or equal to the max integer allowed.

1

2 Answers 2

3

9007199254740992 is the max integer value in JavaScript before you start running into loss of precision issues. Consider this following:

> Math.pow(2, 53) + 1
9007199254740992
> Math.pow(2, 53) + 2
9007199254740994
> Math.pow(2, 53) + 3
9007199254740996
> Math.pow(2, 53) + 4

As can be seen, the resulting value is not accurate in all cases. This is a limitation of floating point numbers, resulting from having only 53 bits dedicated to the coefficient. Once you exceed the range that can be represented with 53 bits plus a sign bit, the floating point representation will become increasingly hit or miss as the value rises.

Sign up to request clarification or add additional context in comments.

Comments

2

JavaScript uses IEEE-754 double-precision numbers, which have roughly 15 digits of decimal precision, but a huge range. In this format, the whole numbers -2^53 through 2^53 can all be reliably represented (this is the precision of the significand of the format). Outside those limits, some whole numbers can be represented but others cannot. E.g., outside that range, there are whole-number gaps.

For instance, double-precision numbers can represent 9,007,199,254,740,992 (2^53) and 9,007,199,254,740,994 (2^53 + 2), but not 9,007,199,254,740,993 (2^53 + 1):

Example console session:

> 9007199254740992
9007199254740992
> 9007199254740992 + 1
9007199254740992
> 9007199254740992 + 2
9007199254740994

Note the second of those. That's not a typo.

14 Comments

You should mention that all integers up to 2^53 are represented precisely in JavaScript. Only after that value the precision for integers drops.
Interesting.. So I guess I just check if the integer is smaller than 9007199254740992, then I use internal math (if I only do division / substraction and %). If it's higher than that number, then I use a bigint.js library?
@Wesley: Yes, I believe 2^53 is the maximum safe value.
@Wesley: The key there is floating point. If you stick with whole numbers, and none of your calculations results in a fractional number (so, you aren't dividing, only adding, subtracting, or mulitplying), you can rely on whole number results. But imprecisions outside of whole numbers are all over the place. The classic example is 0.1 + 0.2, which yields 0.30000000000000004.
@jmar777: Yeah. Even Number.MAX_VALUE + 1e+291 equals Number.MAX_VALUE. But Number.MAX_VALUE + 1e+292 is Infinity.
|