0

I've just run into a peculiar issue with Javascript. An API call returns some JSON as it normally does. One of the ids returned is the long number "10151920335784069". However, in Javascript world that becomes "10151920335784068" (one subtracted).

A quick test in the (Chrome) console demonstrates it:

x = 10151920335784069;
console.log(x);
10151920335784068
x==10151920335784069;
true

Further more:

x==10151920335784067;
true
x==10151920335784066;
false 

What is going on here?

Harel
  • 1,989
  • 3
  • 26
  • 44
  • That ID looks too big to be stored as a number. Store it as a string instead – Bojangles Dec 30 '13 at 23:59
  • If it's really crucial that the calculation is correct you might consider sending the number as a String to PHP/Python/Ruby through an AJAX call. Precision will be a big issue in your case. –  Dec 31 '13 at 00:03

2 Answers2

3

JavaScript (ECMA 262 5th Edition) uses double-precision 64bit numbers in IEEE 754 format. That representation cannot store your value in question exactly so it must round it to the nearest value per the IEEE 754 specification.

Authors and users of APIs that use JSON data should keep this limitation in mind. Many runtime environments (such as JavaScript) have potentially unexpected behavior regarding such numerical values even though the JSON format doesn't impose any such limitations.

maerics
  • 151,642
  • 46
  • 269
  • 291
1

All numerical variables in Javascript are stored as 64-bit floating point integers, so at high levels of precision, with numbers above 32 bits, it will round and give you slightly inaccurate numbers

If you want to check if two numbers are roughly even, you can use this

if(Math.abs(num-check)/check<1e-8)){
     alert("For most practical intents and purposes, they are equal!");
}
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64