javascript bigint 的 JSON 传输:12000000000002539 转换为 12000000000002540?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8663298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:09:48  来源:igfitidea点击:

JSON transfer of bigint: 12000000000002539 is converted to 12000000000002540?

javascriptjsonbiginteger

提问by feipinghuang

I'm transferring raw data like [{id: 12000000000002539, Name: "Some Name"}]and I'm getting the object [{id: 12000000000002540, Name: "Some Name"}]after parsing, for now server side converting id into string seems to help. But is there a better way to transfer bigint data correctly?

我正在传输原始数据,[{id: 12000000000002539, Name: "Some Name"}]并且[{id: 12000000000002540, Name: "Some Name"}]在解析后获取对象,现在服务器端将 id 转换为字符串似乎有帮助。但是有没有更好的方法来正确传输 bigint 数据?

回答by

The value is actually notexceeding the maximum numeric value in JavaScript (which is "only" 1.7308or so).

该值实际上没有超过 JavaScript 中的最大数值(“仅”1.7 308左右)。

However, the value isexceeding the range of "integral precision". It is not that the wrong number is sent: rather, it is that the literal12000000000002539 can only be represented as precisely as12000000000002540, and thus there was neverthe correct numeric value in JavaScript. (The range of integralsis about +/- 253.)

然而,该值超过的“积分精度”的范围内。并不是发送了错误的数字:而是文字12000000000002539只能精确地表示为12000000000002540,因此JavaScript 中从来没有正确的数值。(积分范围约为 +/- 2 53。)

This is an interesting phenomena of using a double relative-precision(binary64 in IEEE-754 speak) type to store all numeric values, including integers:

这是使用双相对精度(IEEE-754 中的二进制 64)类型来存储所有数值(包括整数)的有趣现象:

12000000000002539 === 12000000000002540 // true

The maximum significant number of decimal digits that be precisely stored as a numeric value is 15 (15.95, really). In the above, there are 17 significant digits, so some of the least-significant information is silently lost. In this case, asthe JavaScript parser/engine reads in the literal value.

精确存储为数值的十进制数字的最大有效位数为 15(实际上为 15.95)。上面有17位有效数字,所以一些最不重要的信息被悄悄丢失了。在这种情况下,JavaScript 解析器/引擎读入文字值时。

The only safe way to handle integral numbers of this magnitude in JavaScript is to use a string literal or to break it down in another fashion (e.g. a custom numeric type or a "bigint library"). However, I recommend just using a string, as it is human readable, relatively compact (only two extra characters in JSON), and doesn't require special serialization. Since the value is just an "id" in this case, I hope that math does not need to be performed upon it :)

在 JavaScript 中处理这种大小的整数的唯一安全方法是使用字符串文字或以另一种方式将其分解(例如自定义数字类型或“bigint 库”)。但是,我建议只使用 string,因为它是人类可读的,相对紧凑(JSON 中只有两个额外的字符),并且不需要特殊的序列化。由于在这种情况下该值只是一个“id”,我希望不需要对其进行数学运算:)

Happy coding.

快乐编码。