Best way to handle very large long numbers in Ajax?

Javascript presents all numbers as doubles with double precision. This means that it loses accuracy when working with numbers on the highest end of the 64-bit Java Long datatype - anything after 17 digits. For example, the number:

714341252076979033 

... becomes:

 714341252076979100 

My database uses long identifiers, and some of them are in the danger zone. I could change the offensive values ​​in the database, but that would be difficult in my application. Instead, right now, I pretty quickly guarantee that the server encodes long identifiers as strings in all ajax responses.

However, I would prefer to deal with this in Javascript. My question is: is there a best practice for forcing JSON parsing to process a number as a string?

+4
source share
2 answers

You need to send your values ​​as strings (i.e. enclosed in quotation marks) to ensure that Javascript will treat them as strings instead of numbers.

I do not know how to get around this.

+8
source

JavaScript represents all numbers as 64b IEEE 754.

If your integer cannot fit into 52 bits, it will be truncated, which is what happened here.

If you need to modify your database, modify it to send 52-bit integers. Or 53-bit signed integers.

Otherwise, send them as strings.

0
source

Source: https://habr.com/ru/post/1346381/


All Articles