Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.Stringify() on big numbers alters the numeric value?

I have a WCF service operation that returns an object with long and List<string> properties. When I test the operation in a WCF application, everything works fine and the values are correct. However, I need to be able to call the service using jQuery and JSON format. The value of the long property apparently changes when I read it back in the OnSucceed function.

After searching I've found that JSON.stringify changes big values. So in code like this:

alert(JSON.stringify(25001509088465005));

...it will show the value as 25001509088465004.

What is happening?

Demo here: http://jsfiddle.net/naveen/tPKw7/

like image 730
Amir Mohsen Avatar asked Dec 27 '11 06:12

Amir Mohsen


People also ask

What happens when you JSON Stringify a string?

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.

Can JSON Stringify throw an error?

Errors and Edge Cases JSON. stringify() throws an error when it detects a cyclical object. In other words, if an object obj has a property whose value is obj , JSON. stringify() will throw an error.

Is JSON Stringify necessary?

The JSON. stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.

Can you JSON Stringify an array of objects?

The JSON. stringify method converts a JavaScript object or value to a JSON string. It can optionally modify or filter values if a replacer function/array is specified.


1 Answers

JavaScript represents numbers using IEEE-754 double-precision (64 bit) format. As I understand it this gives you 53 bits precision, or fifteen to sixteen decimal digits. Your number has more digits than JavaScript can cope with, so you end up with an approximation.

Do you need to do maths operations on this big number? Because if its just some kind of ID you can return it as a string and avoid the problem.

like image 189
nnnnnn Avatar answered Oct 19 '22 17:10

nnnnnn