JSON.parse parses / converts big numbers incorrectly

前端 未结 2 1119
甜味超标
甜味超标 2020-12-16 02:36

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 :

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 02:47

    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.

提交回复
热议问题