[英]Best way to deal with very large Long numbers in Ajax?
Javascript represents all numbers as double-precision floating-point. Javascript将所有数字表示为双精度浮点数。 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.
这意味着它在处理64位Java Long数据类型的最高端的数字时会丢失精度 - 17位数后的任何数据。 For example, the number:
例如,数字:
714341252076979033
... becomes: ......变成:
714341252076979100
My database uses long IDs and some happen to be in the danger zone. 我的数据库使用长ID,有些恰好位于危险区域。 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.
相反,现在我非常费力地确保服务器在所有ajax响应中将Long ID编码为字符串。
However, I'd prefer to deal with this in the Javascript. 但是,我更喜欢在Javascript中处理这个问题。 My question: is there a best practice for coercing JSON parsing to treat a number as a string?
我的问题:是否有强制JSON解析将数字视为字符串的最佳实践?
You do have to send your values as strings (ie enclosed in quotes) to ensure that Javascript will treat them as strings instead of numbers. 您必须将您的值作为字符串发送(即用引号括起来),以确保Javascript将它们视为字符串而不是数字。
There's no way I know of to get around that. 我无法解决这个问题。
JavaScript represents all numbers as 64b IEEE 754 floats. JavaScript将所有数字表示为64b IEEE 754浮点数。
If your integer can't fit in 52 bits then it will be truncated which is what happened here. 如果你的整数不能适合52位,那么它将被截断,这就是这里发生的事情。
If you do need to change your database, change it to send 52 bit integers. 如果确实需要更改数据库,请将其更改为发送52位整数。 Or 53 bit signed integers.
或53位有符号整数。
Otherwise, send them as strings. 否则,将它们作为字符串发送。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.