charles raj
charles raj

Reputation: 11

Js return wrong sum result

In JS 9007199254740992 + 1 should be 9007199254740993.

I'm getting 9007199254740992.

What's going on here?

console.log(9007199254740992 + 1)
// 9007199254740992

Upvotes: 1

Views: 150

Answers (4)

Arun Bohra
Arun Bohra

Reputation: 106

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

Upvotes: 1

Abdulrahman Humayed
Abdulrahman Humayed

Reputation: 29

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

Check here for more details

Alternatively you can use BigInt

Upvotes: 0

Random BoY
Random BoY

Reputation: 16

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);

Upvotes: -2

asportnoy
asportnoy

Reputation: 2534

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())

Upvotes: 2

Related Questions