4

I have a javascript twitter app. If I look at the tweetid in Firebug it returns: 344203233524330497 but when I evaluate it in javascript it is returning 344203233524330500 (rounding the last two numbers).

What is going on?

Any ideas?

Thanks you!

Josh Scott
  • 3,790
  • 7
  • 29
  • 31

2 Answers2

3

The maximum Integer value JavaScript can represent without losing precision is 9007199254740992.

Your number is obviously bigger, so JavaScript will use a floating point number for this, which lacks the precision. So in this case it seems as if the last two numbers were rounded.

Just use the string representation or, if you have to use the actual number value, refer to some BigMath libraries.

Sirko
  • 72,589
  • 19
  • 149
  • 183
3

In Javascript, integers are 64-bit numbers. This means that the highest integer is 253, i.e. 9007199254740992. Numbers higher than this will not be accurate: they will see some "rounding" as a result of the way they are stored internally.

You are clearly evaluating this string as a number. If you want to keep it accurate, you'll have to avoid converting it to a number and keep it as a string.

See this answer for more information about number accuracy in JS,

Community
  • 1
  • 1
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • I am not intentionally evaluating it as a number. I am simply calling tweet.id_str (tweeting being the item from the JSON object I am receiving and id_str being the tweetid received from twitter). Can I force it to view it it as a string? I have tried tweet.id_str.toString() and that doesn't work. – Josh Scott Jun 10 '13 at 22:00
  • How are you receiving the JSON? A JSON number will always become a Javascript number when converted. – lonesomeday Jun 10 '13 at 22:01
  • @resonantmedia Can you post an example JSON response and (a relevant piece of) your code to process it? – Sirko Jun 10 '13 at 22:06