Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

I receive this string from an API :

{ "key" : -922271061845347495 }

When I'm using JSON.parse on this string, it turns into this object:

{ "key" : -922271061845347500 }

As you can see, the parsing stops when the number is too long (you can check this behavior here). It has only 15 exact digits, the last one is rounded and those after are set to 0. Is there a "native" solution to keep the exact value ? (it's an ID so I can't round it)

I know I can use regex to solve this problem but I'd prefer to use a "native" method if it exists.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your assumption that the parsing stops after certain digits is incorrect.

It says here:

In JavaScript all numbers are floating-point numbers. JavaScript uses the standard 8 byte IEEE floating-point numeric format, which means the range is from:

±1.7976931348623157 x 10308 - very large, and ±5 x 10-324 - very small.

As JavaScript uses floating-point numbers the accuracy is only assured for integers between: -9007199254740992 (-253) and 9007199254740992 (253)

You number lies outside the "accurate" range hence it is converted to the nearest representation of the JavaScript number. Any attempt to evaluate this number (using JSON.parse, eval, parseInt) will cause data loss. I therefore recommend that you pass the key as a string. If you do not control the API, file a feature request.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...