简体   繁体   中英

Parsing amount with JSON.parse

Dos it exist a maximum float number with two digits after decimal point that can be parsed with JSON.parse without losing precision?

For example:

JSON.parse('{"amount": 9999999999999.99}')

{amount: 9999999999999.99} // not lose (probably)

JSON.parse('{"amount": 99999999999999.99}')

{amount: 99999999999999.98} // lose

If x is a decimal floating-point number with 15 significant digits or fewer, then converting x to JavaScript's Number type and then converting the result back to a decimal floating-point number with the same number of significant digits produces exactly x , provided the number is within normal bounds. Therefore, all decimal numerals with two digits after the decimal point from “.00” to “9999999999999.99” can be parsed, stored, and reformatted with two digits after the decimal point, and the result will be the original numeral.

The stored value will generally not equal the original value. For example, when “.99” is parsed, the result will be exactly 0.9899999999999999911182158029987476766109466552734375. However, the stored value will be sufficiently close to the original value that, when converted back to the original number of digits, the original value is recovered. Note that you must know the original number of digits; it is not inherently a part of the Number value.

15 is a lower bound for this property. There may be some exponent values for which all 16-digit decimal numerals survive a round trip. However, since 99999999999999.99 (16 digits) produces 99999999999999.98, we know this is not one of those intervals.

If you want to know the specific number between 9999999999999.99 and 99999999999999.99 where this round-trip property first fails, you may have to hunt for it computationally. It many not be a value that is easy to calculate directly by mathematical properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM