Maximum Integer Size in JavaScript

Posted on 2023. Nov 03

On a 64-bit machine, integers in JavaScript can just store between -9223372036854775808 and +9223372036854775807, right? After all that's just - (2^63) to 2^63 - 1 (1 bit is used for the sign). Well, actually NO! JavaScript stores all numeric values as IEEE-754 floating-point doubles. Which in turn means that the mantissa is just 53-bits... Thus, the maximum plain integer you can have is actually 2^53 - 1 or 9007199254740991!!!

Granted, that number is still significantly large and you may never come across an overflow. But an interesting edge case arose at Tumblr when we switched our Post ID format from sequential ints to a timestamp based integer (which tacked on additional randomized integers to be globally unique). The data was already formatted for BigInt in MySQL, and PHP could handle the large integers as well.

The "gotcha" was in the JavaScript world. When the JavaScript client tried to deserialize the huge JSON integers, it ended up just rounding the last few numbers to 000 because it didn't have that level of precision. For example, the Post ID 695653420591448064 would actually become 695653420591448000 if treated as a number.

let postId = 695653420591448064;

// prints 695653420591448000

The only fix at the time was to force the Post IDs to be strings everywhere on the client side (and server side, for consistency). And indeed the number truncation happens during JSON serialization, so there's not really a way around it client side unless you use a custom JSON parser to convert large integers to strings.

This article, and all articles on this blog, were written without the use of any AI, GPT, or Language Learning Models. It's old fashioned I guess.