在 Ajax 中处理非常大的长数字的最佳方法?
Javascript 将所有数字表示为双精度浮点数。这意味着在处理 64 位 Java Long 数据类型最高端的数字(17 位数字之后的任何数字)时,它会失去精度。例如,数字:
714341252076979033
... 变为:
714341252076979100
我的数据库使用长 ID,有些恰好位于危险区域。我可以更改数据库中的违规值,但这在我的应用程序中很困难。相反,现在我相当费力地确保服务器在所有 ajax 响应中将长 ID 编码为字符串。
不过,我更愿意在 Javascript 中处理这个问题。我的问题:是否有强制 JSON 解析将数字视为字符串的最佳实践?
Javascript represents all numbers as double-precision floating-point. This means it loses precision when dealing with numbers at the very highest end of the 64 bit Java Long datatype -- anything after 17 digits. For example, the number:
714341252076979033
... becomes:
714341252076979100
My database uses long IDs and some happen to be in the danger zone. I could change the offending values in the database, but that'd be difficult in my application. Instead, right now I rather laboriously ensure the server encodes Long IDs as Strings in all ajax responses.
However, I'd prefer to deal with this in the Javascript. My question: is there a best practice for coercing JSON parsing to treat a number as a string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须将值作为字符串(即用引号引起来)发送,以确保 Javascript 将它们视为字符串而不是数字。
据我所知,没有办法解决这个问题。
You do have to send your values as strings (i.e. enclosed in quotes) to ensure that Javascript will treat them as strings instead of numbers.
There's no way I know of to get around that.
JavaScript 将所有数字表示为 64b IEEE 754 浮点数。
如果您的整数无法容纳 52 位,那么它将被截断,这就是这里发生的情况。
如果您确实需要更改数据库,请将其更改为发送 52 位整数。或者 53 位有符号整数。
否则,将它们作为字符串发送。
JavaScript represents all numbers as 64b IEEE 754 floats.
If your integer can't fit in 52 bits then it will be truncated which is what happened here.
If you do need to change your database, change it to send 52 bit integers. Or 53 bit signed integers.
Otherwise, send them as strings.