JSON transmission bigint: 12000000000002539 converts to 12000000000002540?

I pass raw data such as [{id: 12000000000002539, Name: "Some Name"}] , and I get the object [{id: 12000000000002540, Name: "Some Name"}] after parsing, since now the conversion of id to string server side helps. But is there a better way to transfer bigint data correctly?

+47
json javascript biginteger
Dec 29 2018-11-12T00:
source share
1 answer

The value does not actually exceed the maximum numerical value in JavaScript (it is "only" 1.7 308 or so).

However, the value exceeds the range of "integral accuracy". It's not that the wrong number was sent: rather, the letter 12000000000002539 can only be represented as 12000000000002540, and therefore, JavaScript did not have the correct numeric value. (the range of integrals is about +/- 2 53. )

This is an interesting phenomenon of using double relative accuracy (binary code in IEEE-754 mode) to store all numerical values, including integers:

 12000000000002539 === 12000000000002540 // true 

The maximum significant number of decimal digits that is exactly stored as a numeric value is 15 (15.95, really). In the above example, there are 17 significant digits, so some of the least significant data is silently lost. In this case, when the JavaScript parser / engine reads in literal meaning.

The only safe way to handle the integral numbers of this value in JavaScript is to use a string literal or break it in another way (for example, a custom number type or the "Bigint library" ). However, I recommend just using the string, as it is human-readable, relatively compact (just two extra characters in JSON) and does not require special serialization. Since in this case the value is just "id", I hope that the math should not be done on it :)

Happy coding.

+84
Dec 29 '11 at 3:10
source share



All Articles