16

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?

2
  • Do you need to do calculations on the number in javascript? If not you could just make it a string in the json for use on the client side.
    – clav
    Mar 28, 2013 at 18:46
  • @ Moshe: FWIW, this has nothing to do with JSON, parseInt('6855337641038665531', 10) returns 6855337641038666000, too, for the reasons Kolink explains. Mar 28, 2013 at 18:47

4 Answers 4

10

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.

0
7

It's too big of a number. JavaScript uses double-precision floats for numbers, and they have about 15 digits of precision (in base 10). The highest integer that JavaScript can reliably save is something like 251.

The solution is to use reasonable numbers. There is no real way to handle such large numbers.

3
  • Well, no way to handle them using double-precision IEEE-754s, anyway. :-) Mar 28, 2013 at 18:46
  • 7
    @Niet the Dark Absol "The solution is to use reasonable numbers." you have got to be kidding me. There are cases where it's valid to say "you want to do the wrong thing" but when javascript not properly supports signed 64 bit integers like literally every other language on this planet then its definitively not the users fault.
    – Wulf
    Apr 24, 2015 at 13:02
  • 3
    @Wulf That is a problem with JavaScript. Not with JSON. Apr 24, 2015 at 14:31
6

The largest number JavaScript can handle without loss of precision is 9007199254740992.

1
  • 1
    Number.MAX_SAFE_INTEGER
    – Qi Fan
    Feb 7, 2018 at 1:06
3

I faced this issue some time ago, I was able to solve using this lib: https://github.com/josdejong/lossless-json

You can check this example:

let text = '{"normal":2.3,"long":123456789012345678901,"big":2.3e+500}';
// JSON.parse will lose some digits and a whole number:
console.log(JSON.stringify(JSON.parse(text)));
// '{"normal":2.3,"long":123456789012345680000,"big":null}'      WHOOPS!!!
// LosslessJSON.parse will preserve big numbers:
console.log(LosslessJSON.stringify(LosslessJSON.parse(text)));
// '{"normal":2.3,"long":123456789012345678901,"big":2.3e+500}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.