0

How can this be explained that I get a result that ends in 92 for the first two calculations, and 94 for the third one?

    console.log(Number.MAX_SAFE_INTEGER + 1); //...92
    console.log(Number.MAX_SAFE_INTEGER + 2); //...92
    console.log(Number.MAX_SAFE_INTEGER + 3); //...94
brainoverflow
  • 691
  • 2
  • 9
  • 22
  • Weird, I get 9007199254740992, 9007199254740992 and 9007199254740994 in Chrome – phuzi Jun 10 '21 at 13:02
  • 1
    Numbers beyond `Number.MAX_SAFE_INTEGER` cannot be represented accurately and are rounded which leads to mathematical errors. See: [What Every Programmer Should Know About Floating-Point Arithmeti](https://floating-point-gui.de/) – Yousaf Jun 10 '21 at 13:03

1 Answers1

0

Based on this Number.MAX_SAFE_INTEGER is the largest integer in your safe calculation and any number larger than that is not safe.

Edit

For larger than Number.MAX_SAFE_INTEGER use BigInt such as:

BigInt(Number.MAX_SAFE_INTEGER) + BigInt(2)

 alert(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)); //9007199254740992n
 alert(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(2)); //9007199254740993n
 alert(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(3)); //9007199254740994n
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42