简体   繁体   中英

JSON response from Jquery.ajax is rounding larger number so I can't get correct value

I am performing an AJAX get request and this is the response I get in a program like Paw/Postman:

[
  {
    "registrantKey": 4131401026087862797,
  }
]

However when I do:

.done(function(data, textStatus, jqXHR) {
    $.each(data, function(index){
    console.log(data[index].registrantKey);
    });
})

it is treating this registrant key value as a large number and is rounding off the last numbers so the value being printed to the console is: 4131401026087863000. How do I get the original value as shown in Paw/Postman. I don't need to perform any math operations on it I just need the value. I tried experimenting with the toString() method but I couldn't get this to work. Your help would be much appreciated.

update Unfortunately this just isn't possible in javascript. The only solution is to use another language or to try and get original developers to return value as a string. Thanks Rory and Madalin.

The issue is due to the precision of JS and has nothing to do with jQuery or AJAX. In JS a number can only contain a maximum of 16 integers, up to a maximum of 9,007,199,254,740,991 (aka Number.MAX_SAFE_INTEGER )

If you need to display a larger number then you would have to work with it as a string, but be aware that it will be rounded down to the max precision JS can use if you attempt to convert it to a Number type.

If you can access to your json as string and not as object (maybe in the jqXHR object), you can transform all numbers to string like this :

jsonText = jsonText.replace(/([^\\D]\\d+[^\\D])/g, "\\"$1\\"").replace(/""/g, "\\"");

(Be careful with my regex, i don't really sure if it works in any case)

And after load your jsonText as an object.

My first solution was: Send json string as text/plain from backend; With horroble regex replace numbers with strings then parse to object.

Then after some bugs we modified json serializer(jackson lib) to write as string if value is instance of Number; Send string as application/json from backend; Removed frontend code since jquery does parsing if content type is json;

Operating with big numbers is done by BigNumber JQ plugin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM