JSON/JavaScript and large 64 bit integer values

JavaScript represents all numbers internally as 64 bit floating point values (see the ECMAScript spec here). This means JavaScript runtimes are not able to handle integer values larger than 9007199254740992 (2^53).

Note that all the positive and negative integers whose magnitude is no greater than 2^53 are representable in the Number type

Where this often causes problems is when a numeric JSON value is parsed by a JavaScript runtime, and the numeric value was generated by a system that does support 64bit (or larger) integers (e.g. Java or a database), and the actual value happens to exceed 2^53. The JavaScript runtime will (on FireFox and Chrome at least) round the value down, rather than reporting an error.

Probably fair to say that nearly all the time large 64 bit values are being used, they are being used as unique identifiers (as opposed to an outright measure of some quantity). In this case the usual workaround is to convert the numeric value to a string before converting it to JSON.

So if you’re transporting integer values over JSON you need to double check if the values can exceed the +/-2^53 range that JavaScript supports

Advertisements