Home > Web Front-end > JS Tutorial > Why Are Large Numbers Rounded Incorrectly in JavaScript JSON Parsing?

Why Are Large Numbers Rounded Incorrectly in JavaScript JSON Parsing?

Mary-Kate Olsen
Release: 2024-12-17 15:27:10
Original
362 people have browsed it

Why Are Large Numbers Rounded Incorrectly in JavaScript JSON Parsing?

Large Numbers Erroneously Rounded in JavaScript

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template