Some question about big numbers in JS

I am doing some research how to deal with numbers:
how to avoid scientific notation
also
about toFixed() and toPrecision()

It’s all good, but I for now need some explanation about output below:

for (let i = 1; i < 10; i++) {
  console.log(Number.MAX_SAFE_INTEGER, ' + ',
              i, ' ???   ',
              Number.MAX_SAFE_INTEGER + i)
}

/*
Output:

9007199254740991  +  1  ???    9007199254740992
9007199254740991  +  2  ???    9007199254740992
9007199254740991  +  3  ???    9007199254740994
9007199254740991  +  4  ???    9007199254740996
9007199254740991  +  5  ???    9007199254740996
9007199254740991  +  6  ???    9007199254740996
9007199254740991  +  7  ???    9007199254740998
9007199254740991  +  8  ???    9007199254741000
9007199254740991  +  9  ???    9007199254741000
*/

That is kind of the whole point. You can not reliably work with computations of numbers above MAX_SAFE_INTEGER without using BigInt.

1 Like
Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2
// true
2 Likes

As for your output above, it may work for the first few small increments, but try something like + 20. As you can see, some of them work and some of them don’t. It’s just the nature of how numbers are stored in computers.

1 Like

Thanks.
I was just doing some more research about BigInt. Somehow I didn’t find it right away.