JSON.parse does not handle or convert large numbers correctly

My problem is very simple, but I'm not sure if there is a "native" solution using JSON.parse.

I get this line from the API:

{ "key" : -922271061845347495 } 

When I use JSON.parse in this line, it turns into this object :

 { "key" : -922271061845347500 } 

As you can see, parsing stops when the number is too large (you can check this behavior here ). It has only 15 exact digits, the last is rounded, and those that are set after 0. Is there a "native" solution to preserve the exact value? (this is an identifier, so I cannot round it)

I know that I can use regex to solve this problem, but I would prefer to use the "native" method if it exists.

+8
source share
2 answers

Your assumption that parsing stops after entering certain numbers incorrectly.

It says here :

In JavaScript, all numbers are floating point numbers. Using JavaScript, the standard 8-byte IEEE floating point number format, which means a range from:

± 1.7976931348623157 x 10 308 is very large and ± 5 x 10 -324 is very small.

Because JavaScript uses floating point numbers, accuracy is only provided for integers: -9007199254740992 (-2 53 ) and 9007199254740992 (2 53 )

You are listed outside the "exact" range, so it is converted to the closest representation of the JavaScript number. Any attempt to evaluate this number (using JSON.parse, eval, parseInt) will result in data loss. Therefore, I recommend passing the key as a string. If you do not control the API, write a function request.

+16
source

The number is too large for proper analysis.

One solution is:

  1. Pre-processing your string from the API to convert it to a string before parsing.
  2. Preform normal parsing
  3. If you wish, you can convert it back to a number for your own purposes.

Here is RegExp to convert all the numbers in your string (hereafter :) to strings:

  // convert all number fields into strings to maintain precision // : 922271061845347495, => : "922271061845347495", stringFromApi = stringFromApi.replace(/:\s*(-?\d+),/g, ': "$1",'); 

Regex explanation:

  • \ s * any number of spaces
  • -? one or zero "-" characters (support for negative numbers)
  • \ d + one or more digits
  • (...) will be placed in the variable $ 1
+1
source

All Articles