0

so I ran into this issue with javascript Number() function, it seems to return the wrong value: the following code: Number("10153396863200835")
returns 10153396863200836, not 10153396863200835

but if I do Number("10153396863200836") it returns 10153396863200836 and Number("10153396863200834") returns 10153396863200834

so I'm confused what's going on? thanks

rainman333
  • 31
  • 6

1 Answers1

5

Because JavaScript's numbers are IEEE-754 double-precision binary floating point (frequently known as "double"). They have only about 15 digits of decimal precision. Your number, 10153396863200835, is much larger than that.

In doubles, the maximum whole number before we stop being able to represent the next whole number is 9,007,199,254,740,9921. 9,007,199,254,740,993 cannot be represented by doubles; 9,007,199,254,740,994 can. That's because at that scale, the least significant bit is worth 2 decimal. The further you go, the bigger those gaps get, as the least significant bit starts being worth 4 decimal, then 8, then...


Modern JavaScript has a handy constant for the value right before this value, 9,007,199,254,740,991: Number.MAX_SAFE_INTEGER. It's defined as the last whole number in a double where adding 1 gives you the next consequtive whole number. The name is slightly misleading, as 9,007,199,254,740,994 or indeed 10,153,396,863,200,836 aren't going to suddenly stop having those values, it's just that math with them starts getting...interesting.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875