JSON.parse 错误地解析/转换大数字

2022-01-17 00:00:00 json floating-point numbers javascript

我的问题很简单,但我不确定是否有使用 JSON.parse 的本机"解决方案.

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

我从 API 收到这个 字符串:

I receive this string from an API :

{ "key" : -922271061845347495 }

当我在这个字符串上使用 JSON.parse 时,它​​变成了这个 object:

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

{ "key" : -922271061845347500 }

如您所见,当数字太长时解析停止(您可以检查此行为here).它只有 15 位精确数字,最后一位是四舍五入的,后面的数字设置为 0.是否有本机"解决方案来保持精确值?(这是一个ID,所以我不能四舍五入)

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.

推荐答案

您对解析在某些数字后停止的假设是不正确的.

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

上面写着这里:

在 JavaScript 中,所有数字都是浮点数.JavaScript 使用标准的 8 字节 IEEE 浮点数字格式,这意味着范围来自:

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 - 非常大,±5 x 10-324 - 非常小.

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

由于 JavaScript 使用浮点数,因此只能确保准确性对于介于:-9007199254740992 (-253) 和 9007199254740992 之间的整数(253)

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

您的数字位于准确"范围之外,因此它被转换为 JavaScript 数字的最接近的表示形式.任何评估此数字的尝试(使用 JSON.parse、eval、parseInt)都会导致数据丢失.因此,我建议您将密钥作为字符串传递.如果您不控制 API,请提交功能请求.

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.

相关文章