-1

After I read #magically-increasing-numbers,

so I was wondering about If made calculator with JS how and user put a large number like 9999999999999999

const result = 9999999999999999 + 2
console.log(result)

Correct result should be 10000000000000001 not 10000000000000002

I tried with Number() or even parseFloat() but still does not work.

How we can deal with that?

l2aelba
  • 21,591
  • 22
  • 102
  • 138

1 Answers1

1

As you already discovered, you ran into an issue with the limited precision of floating point numbers, since your number is outside of the range of "safe integers" which are stored with full precision (it is larger than Number.MAX_SAFE_INTEGER = 2^53 - 1).

If you only need integers, the native BigInt type will work just fine (as long as you take care of converting things to/from a BigInt in the right way):

const result = 9999999999999999n + 2n
console.log(result) // 10000000000000001n (not printed in Stack Overflow somehow)

If you need decimals too, then you will need a library handling arithmetics with big arbitrary-precision decimals, such as bignumber.js, to name one of many.

CherryDT
  • 25,571
  • 5
  • 49
  • 74