1

In JS 9007199254740992 + 1 should be 9007199254740993.

I'm getting 9007199254740992.

What's going on here?

console.log(9007199254740992 + 1)
// 9007199254740992
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – iBug Oct 04 '22 at 16:22
  • You can use BigInt() – Sifat Haque Oct 04 '22 at 16:26
  • @iBug Sorry, here i have not used floating numbers right? still why we get wrong values? still if js treats somehow as float, is there any way to overcome this issue? – charles raj Oct 04 '22 at 16:29

4 Answers4

2

You can use BigInts to prevent overflow like this.

console.log((9007199254740992n + 1n).toString())

Or, if it's a variable:

const num = "9007199254740992";
console.log((BigInt(num) + 1n).toString())
asportnoy
  • 2,218
  • 2
  • 17
  • 31
1

From MDN:

Double precision floating point format only has 52 bits to represent the mantissa, so it can only safely represent integers between -(253 – 1) and 253 – 1.

"Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information.

If you really want to use numbers larger than that one you can use BigInt

Arun Bohra
  • 104
  • 1
  • 10
0

9007199254740992 is the largest allowed integer in JS (2^53 – 1)

Check here for more details

Alternatively you can use BigInt

  • 1
    `(2^53 – 1)` is `Number.MAXIMUM_SAFE_INTEGER` but it is `9007199254740991` not `9007199254740992 `. And anyway, larger integers are also allowed. For example, `Number.MAX_VALUE`. – MikeM Oct 04 '22 at 16:39
  • Please fix the max safe number value. – drdrej Oct 08 '22 at 09:21
-2

Try to shrink the number, Javascript has a hard time processing large values. Or if you don't want to, turn the big number into a value.

const bigNum = 9007199254740992;
console.log(bigNum + 1);
Random BoY
  • 16
  • 2