bigint的JSON传输:12000000000002539转换为12000000000002540? [英] JSON transfer of bigint: 12000000000002539 is converted to 12000000000002540?

查看:466
本文介绍了bigint的JSON传输:12000000000002539转换为12000000000002540?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

该值实际上是不是超过JavaScript中的最大数值(仅1.7 308 左右)。

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

但是,值 超出积分精度的范围。并不是发送了错误的数字:而是 literal 12000000000002539 只能表示为 12000000000002540,因此从不 JavaScript中的正确数值。 (积分范围约为+/- 2 53 。)

However, the value is exceeding the range of "integral precision". It is not that the wrong number is sent: rather, it is that the literal 12000000000002539 can only be represented as precisely as 12000000000002540, and thus there was never the correct numeric value in JavaScript. (The range of integrals is about +/- 253.)

这是一个使用 双相对精度 (IEEE-754中的binary64)类型,用于存储所有数值,包括整数:

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

12000000000002539 === 12000000000002540 // true

最大有效数字精确存储为数值的十进制数字是15(真的是15.95)。在上面,有17个有效数字,因此一些最不重要的信息会无声地丢失。在这种情况下, as JavaScript解析器/引擎读入文字值。

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, as the JavaScript parser/engine reads in the literal value.

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

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 :)

快乐编码。

这篇关于bigint的JSON传输:12000000000002539转换为12000000000002540?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆