Javascript无法正确解析JSON中的大数字 [英] Javascript not parsing large number in JSON correctly

查看:106
本文介绍了Javascript无法正确解析JSON中的大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以JSON格式从网络服务器传回已批准的推文列表。当我在我的浏览器中访问URL: http:// localhost:8000 / showtweets /?after_id = 354210796420608003 时,我得到以下JSON:

I'm passing back a list of approved tweets from a webserver in JSON format. When I go to the URL: http://localhost:8000/showtweets/?after_id=354210796420608003 in my browser I get the following JSON:

   [{
    "date": "2013-07-08T12:10:09",
    "text": "#RaspberryPi ist auf dem Weg :-)",
    "author_pic_url": "http://a0.twimg.com/profile_images/1315863231/twitter_normal.jpg",
    "id": 354210796420608004,
    "author": "switol"
}]

其ID为: 354210796420608004

当我从Javascript拨打GET电话时,号码会改变:

When I make a GET call from Javascript, the number changes:

function TweetUpdater() {
}

TweetUpdater.latest_id = 0;
TweetUpdater.undisplayed_tweets = new Array();

TweetUpdater.prototype.get_more_tweets = function () {
    // var since_id = parseFloat(TweetUpdater.get_latestlatest_id;
    // alert(since_id);
    var get_tweets_url = "/showtweets/?after_id="+TweetUpdater.latest_id;
    $.get(get_tweets_url, function (tweets) {
        if (tweets.length > 0) {

            /////////////////////////////////////////////////////////
            alert(tweets[0].id+", "+ tweets[0].text); <<<<< THIS LINE
            /////////////////////////////////////////////////////////

            TweetUpdater.latest_id = tweets[0].id;
            for (var i = 0; i < tweets.length; i++) {
                TweetUpdater.undisplayed_tweets.push(tweets[i]);
            }
        }
    }, "json");
};

此代码提醒: 354210796420608000,#RaspberryPi ist auf dem Weg: - )

354210796420608004!= 3 54210796420608000

354210796420608004 != 354210796420608000

很奇怪。

推荐答案

不,不是很奇怪。 JS将所有数字表示为double,并且随着整数的增加,您在某些时候会丢失精度。有关详细信息,请参阅数字可以达到的最高整数值是什么,而不会丢失精度?

No, not very odd. JS represents all numbers as double, and with growing integers you loose precision at some point. See What is JavaScript's highest integer value that a Number can go to without losing precision? for details.

要解决这个问题,只需将 id 设为一个字符串 - 无论如何你都没有用它进行计算。您必须在原始JSON中执行此操作,否则精度损失发生在 JSON.parse 已经。

To solve the problem, simply make the id a string - you're not doing calculations with it anyway. You'll have to do that in the original JSON though, otherwise the precision loss happens at JSON.parse already.

这篇关于Javascript无法正确解析JSON中的大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆