user429620
user429620

Reputation:

Javascript max int

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.

Upvotes: 4

Views: 2188

Answers (2)

jmar777
jmar777

Reputation: 39649

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.

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074276

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.

Upvotes: 2

Related Questions