Window.parseJSON truncates large numbers

Possible duplicate:
Big numbers mistakenly rounded in Javascript

I use jQuery.parseJSON () to take a json string and make it an object. The json string is placed by the script tag of our server with the initial markup. The json string contains values ​​that reference different resources on our website.

There is a problem in implementing this, which was missed in development, and is now starting to start it. Our server is based on Java. Numeric values ​​are presented primarily as Longs. So the json string will have things like "..." id ': 25783071737028608 ... ". This is a problem because this value exceeds the maximum value for the JS Number type by two integer permissions of 10. In this case, the number is rounded: 25783071737028610, which leads to various data inconsistencies.

This type of template is ubiquitous on our website, and values ​​represent values ​​from our database. I want to avoid massive database refactoring. I also want to avoid just passing things to the browser as strings ("..." id ': "25783071737028608" ... "because finding every instance of a long javascript passed will require massive refactoring of our database.

Anyway, to represent Java a long type in JavaScript? If not (which, I think so), are there any creative works that you could use to solve such problems?

+4
source share
3 answers

As you already mentioned, your values ​​exceed the maximum integer value in JavaScript, so you can do nothing other than pass your values ​​as strings or write your own JSON JavaScript parser (or modify jQuery) and parse long integer values ​​as strings.

+3
source

You will need to encode the number as a string on the server or write your own JSON parser in JavaScript to handle too large numeric constants.

(There is at least one more question about SO, which is almost the same as this one.)

edit - it’s a pity that I missed the part where you said that you can’t change the encoding. Well, the good news is that you should be able to use the JSON2 parser source and modify it, perhaps to interpret all numerical constants as strings, or even more than a certain number of digits.

In fact, the json2.js parser is just a sanitizer that ensures that calling eval() does not cause a problem. Well, I think this approach is your only option. If the structure of your JSON expressions is regular and fairly simple, you can "fix" their preliminary analysis using a regular expression, but if not, it will be a JSON parser in JavaScript.

0
source

Numbers in JavaScript are double precision floating values, which means they have about 15 precision digits. a number with more than 15 digits is approximated in the same way as 1/3 .

Even if you can change it to a string, you cannot manipulate the number in any way. I honestly can't think of any reason why you will have ID numbers in quadrillion ...

-1
source

All Articles