Best way to deal with very large Long numbers in A

2019-05-01 19:55发布

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?

2条回答
▲ chillily
2楼-- · 2019-05-01 20:13

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.

查看更多
闹够了就滚
3楼-- · 2019-05-01 20:14

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.

查看更多
登录 后发表回答