Search code examples
javascriptjson

Parse json in javascript - long numbers get rounded


I need to parse a json that contains a long number (that was produces in a java servlet). The problem is the long number gets rounded.

When this code is executed:

var s = '{"x":6855337641038665531}';
var obj = JSON.parse(s);
alert (obj.x);

the output is:

6855337641038666000

see an example here: http://jsfiddle.net/huqUh/

why is that, and how can I solve it?


Solution

  • As others have stated, this is because the number is too big. However, you can work around this limitation by sending the number as a string like so:

    var s = '{"x":"6855337641038665531"}';
    

    Then instead of using JSON.parse(), you can use a library such as javascript-bignum to work with the number.