Best way to deal with very large Long numbers in Ajax?

旧时模样 提交于 2019-12-22 06:45:02

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5525783/best-way-to-deal-with-very-large-long-numbers-in-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!