Moshe Shaham
Moshe Shaham

Reputation: 15984

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?

Upvotes: 21

Views: 18952

Answers (5)

meepo
meepo

Reputation: 19

const bigJSON = '{"gross_gdp": 12345678901234567890}';
const bigObj = JSON.parse(bigJSON, (key, value, context) => {
  if (key === "gross_gdp") {
    // Ignore the value because it has already lost precision
    return BigInt(context.source);
  }
  return value;
});

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

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.

There is no real way to handle such large numbers.

Upvotes: 9

Deivison Sporteman
Deivison Sporteman

Reputation: 2382

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}'

Upvotes: 5

Sergiu Toarca
Sergiu Toarca

Reputation: 2749

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.

Upvotes: 13

jmar777
jmar777

Reputation: 39649

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

Upvotes: 10

Related Questions