9

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"
}]

Which has an id of: 354210796420608004.

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");
};

This code alerts: 354210796420608000, #RaspberryPi ist auf dem Weg :-)

354210796420608004 != 354210796420608000

Very odd.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
tompreston
  • 630
  • 7
  • 24
  • 3
    JS "integers" are at most 2^53 = 9007199254740992. Yours is a lot bigger. look here http://stackoverflow.com/questions/4557509/javascript-summing-large-integers – Bakudan Jul 08 '13 at 16:02

2 Answers2

14

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.

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • There's also [bignum](https://github.com/jtobey/javascript-bignum) libraries for javascript in the event the ID does need to be worked with arithmetically. – Mike Jul 08 '13 at 16:14
  • I made sure that the id was converted to a string before being passed back from the server. This solve the issue. Thanks. – tompreston Jul 09 '13 at 08:22
  • Another library to solve this: https://github.com/josdejong/lossless-json – Jos de Jong Aug 17 '23 at 12:54
3

Try using id_str instead of id while using twitter API, It should work. see this https://dev.twitter.com/discussions/11284.

Piyuesh
  • 1,066
  • 1
  • 9
  • 18