-2

When I run the following:

parseInt('96589218797811259658921879781126'.slice(0, 16), 10);

the output is

9658921879781124

whereas the expected is, as you can see:

9658921879781125

What is the cause? I understand vaguely in googling around that there are issues with large numbers in JS and that this indeed appears to be above that threshold, but I don't know what to do about it, or what is happening in this specific case. Thank you.

Edit: Thanks for the answers, I see that depending on an integer this size is bad news. The reason for using an integer is because I need to increment by one, then compare to the rest of the string. In this case, the first half of the string should equal the second half after incrementing the first half by one. What is an alternative approach?

Dan Oswalt
  • 2,201
  • 2
  • 14
  • 24
  • 1
    Possible duplicate of [What is JavaScript's highest integer value that a number can go to without losing precision?](https://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin) – Patrick Roberts May 14 '18 at 05:44
  • `9658921879781124 > Number.MAX_SAFE_INTEGER` – Jaromanda X May 14 '18 at 05:44
  • Possible duplicate of https://stackoverflow.com/questions/5450012/how-to-convert-a-string-to-long-in-javascript – Nandan Chaturvedi May 14 '18 at 05:48
  • Looks like the XY problem, what do you want to do with the number? – user202729 May 14 '18 at 05:51
  • FYI: [`For the next range, from 253 to 254, everything is multiplied by 2, so the representable numbers are the even ones, etc.`](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) for why `9658921879781125` becomes `9658921879781124`. – momocow May 14 '18 at 05:51
  • Why is this down-voted? I genuinely don't understand – Dan Oswalt May 14 '18 at 06:27

1 Answers1

1

It is not a JavaScript issue.

JavaScript uses the double-precision 64-bit floating point format (IEEE 754) to store both integer and rational numbers.

This format allows the exact representation of integer numbers between -253 and 253 (-9007199254740992 to 9007199254740992). Outside this interval, some integer values cannot be represented by this format; they are rounded to the nearest integer value that can be represented. For example, from 253 to 254, everything is multiplied by 2, so the representable numbers are the even ones.

The JavaScript global object Number provides the constant Number.MAX_SAFE_INTEGER that represents the maximum integer value that can be stored by the IEEE 574 format (253-1).

It also provides the method Number.isSafeInteger() you can use to find out if an integer number can be safely stored by the Number JavaScript type.

The number you use (9658921879781124) is too large to be stored correctly in JavaScript or any other language that uses the double-precision floating point format to store the numbers.

axiac
  • 68,258
  • 9
  • 99
  • 134