When parsed using JSON.parse, large numerical values in JSON strings can sometimes be rounded incorrectly in JavaScript. This issue arises because JavaScript's number type has a limited capacity, which is described in the IEEE-754 double-precision binary floating-point format specification.
JavaScript can accurately represent numbers up to approximately 9007199254740991 (Number.MAX_SAFE_INTEGER). Beyond this value, the format loses precision, and numbers may be rounded to the nearest representable value.
For example, the following code demonstrates this behavior:
const jsonString = '{"id":714341252076979033,"type":"FUZZY"}'; const jsonParsed = JSON.parse(jsonString); console.log(jsonString, jsonParsed);
When executed, the value of jsonParsed.id is incorrectly rounded to 714341252076979100. This is because the original value, 714341252076979033, is outside the safe integer range.
To avoid this issue, consider using string representations for large numerical values instead of numbers. Alternatively, you can use the BigInt data type in ES2020, which supports arbitrarily large integers. However, note that BigInt values cannot be natively serialized to JSON, so you will need to use a custom serializer/deserializer.
The above is the detailed content of Why Are Large Numbers Rounded Incorrectly in JavaScript JSON Parsing?. For more information, please follow other related articles on the PHP Chinese website!