سؤال

Possible Duplicate:
Large numbers erroneously rounded in Javascript

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

There's problem in the implementation of this that was overlooked in development, and is now starting to rear it's head. Our server is java based. Numeric values are for the most part represented as Longs. So the json string will have things like "...'id': 25783071737028608...". This is a problem because this value exceeds the max value for a JS Number type by two whole powers of 10. In this case the number get rounded up: 25783071737028610, which causes all sorts of data inconsistency issues.

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

Is there anyway to represent a Java long type in JavaScript? If no (which I believe to be the case) is there any creative work arounds that you might have used to resolve similar issues?

هل كانت مفيدة؟

المحلول

As you already mentioned your values exceed maximum integer value in JavaScript, so there's nothing you can really do other than passing your values as strings or writing your own JavaScript JSON parser (or modifying jQuery one) and parse long integer values as strings.

نصائح أخرى

You'll have to encode the number as a string at the server, or else write your own JSON parser in JavaScript to deal with too-big numeric constants.

(There's at least one other question on SO that's almost the same as this.)

edit — sorry I missed the part where you said you couldn't change the encoding. Well the good news is that you should be able to take the JSON2 parser source and modify it, perhaps to interpret all numeric constants as strings, or else ones more than a certain number of digits long.

Oops well the json2.js "parser" is just a sanitizer that ensures calling eval() won't cause a problem. Well still, I think this approach is your only option. If the structure of your JSON expressions is regular and simple enough, you might be able to "fix" them pre-parse with a regex, but if not then a JSON parser in JavaScript is it.

Numbers in JavaScript are double-precision floats, meaning they have around 15 digits of precision. number with more then 15 digits are approximated in the same way that 1/3 is.

Even if you could change it to a string, you wouldn't be able to manipulate the number in any way. I honestly can't think of any reason why you would have ID numbers in the quadrillions...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top