Javascript Rounding numeric strings from JSON

I have a twitter javascript application. If I look at the tweetid in Firebug it will return: 344203233524330497, but when I evaluate it in javascript, it returns 344203233524330500 (rounding off the last two numbers).

What's happening?

Any ideas?

Thank you!

+4
source share
2 answers

In Javascript, integers are 64-bit numbers. This means that the highest integer is 2 53 i.e. 9007199254740992 . The numbers above this will not be exact: they will see some โ€œroundingโ€ as a result of how they are stored inside.

You clearly evaluate this line as a number. If you want to keep it accurate, you do not have to convert it to a number and store it as a string.

See this answer for more information on precision numbers in JS,

+3
source

The maximum integer JavaScript value can represent without loss of precision 9007199254740992.

Your number is clearly larger, so JavaScript will use a floating point number for this, which is not accurate. Therefore, in this case, it seems that the last two numbers are rounded.

Just use a string representation or, if you need to use the actual value of a number, check out some BigMath libraries.

+3
source

Source: https://habr.com/ru/post/1485524/


All Articles