Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 704
Moshe Shaham Avatar asked Mar 28 '13 18:03

Moshe Shaham


People also ask

How do I round a number in JSON?

let num = 2.575949004696; num = num. toFixed(3); It returns a string with the rounded number.

What does JSON Stringify () method do?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Is JSON parse and Stringify slow?

parse: 702 ms. Clearly JSON. parse is the slowest of them, and by some margin.

What is reverse of JSON Stringify?

JSON. parse is the opposite of JSON. stringify .


2 Answers

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.

like image 93
Sergiu Toarca Avatar answered Nov 09 '22 23:11

Sergiu Toarca


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.

like image 33
Niet the Dark Absol Avatar answered Nov 09 '22 23:11

Niet the Dark Absol