JSON.parse错误地解析/转换大数字 [英] JSON.parse parses / converts big numbers incorrectly
问题描述
我的问题很简单,但我不确定是否有使用JSON.parse的原生解决方案。
我收到这个
$ b
{key:-922271061845347495}
/ code>
当我在这个字符串上使用JSON.parse时,它会变成这个 对象 :
{key:-922271061845347500}
正如您所看到的,解析在数字太长时停止(您可以检查此行为 here )。它只有15个精确的数字,最后一个是四舍五入的,后面的都是0.是否有一个原生的解决方案来保持精确的值? (这是一个ID,所以我不能把它)
我知道我可以使用正则表达式来解决这个问题,但我更喜欢使用本地的方法,如果它是存在的。
在这里:
在JavaScript中,所有数字都是浮点数。 JavaScript使用
标准的8字节IEEE浮点数字格式,这意味着
的范围是:
±1.7976931348623157 x 10 308非常大,±5×10 -324非常小。
由于JavaScript使用浮点数准确性只保证
之间的整数:-9007199254740992(-2 53 )和9007199254740992
(2 53 )
您的数字位于准确范围之外,因此将其转换为JavaScript数字的最接近的表示。任何尝试评估这个数字(使用JSON.parse,eval,parseInt)都会导致数据丢失。因此,我建议您将密钥作为字符串传递。如果您不控制API,请提交功能请求。
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.
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.
这篇关于JSON.parse错误地解析/转换大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!