Home >Web Front-end >JS Tutorial >Why are Large Numbers Truncated When Using JSON.parse() in JavaScript?
Large Numbers Incorrectly Truncated in JavaScript
The question arises why large numbers, such as 714341252076979033, are incorrectly rounded when parsed from a JSON string using JSON.parse(). The resulting value in the console shows a truncated number, with significant digits removed.
Answer
This phenomenon occurs because JavaScript's number type, which is based on IEEE-754 double-precision floating point, has limitations in representing large integers. Double-precision floating point has a maximum safe integer value of 9,007,199,254,740,991 (Number.MAX_SAFE_INTEGER). Beyond this point, the precision of floating-point representation decreases, resulting in rounding of consecutive integers.
In this specific case, the large number being parsed exceeds Number.MAX_SAFE_INTEGER by a significant margin. Consequently, the rounding algorithm used by JavaScript truncates the least significant digits to represent the number as closely as possible within the limitations of its floating-point system.
Workaround
To avoid this issue, it is recommended to use BigInt for representing large integers that are beyond the capacity of JavaScript's number type. BigInt is a data type added in ES2020 that can handle integers of arbitrary length. However, it is important to note that BigInt is not supported natively in JSON, so alternative methods must be used to represent and parse large integers.
One approach is to use a reviver function when parsing JSON. The reviver function can convert a string representation of a large integer to a BigInt object, allowing it to be handled correctly within the JavaScript application.
The above is the detailed content of Why are Large Numbers Truncated When Using JSON.parse() in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!