Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...