0

When comparing the two values in node js the console is logging out that both value are equal when they are not.

let num = 9999999999999999999999999999999999;
if (num === 9999999999999999992999999999999999) {
        console.log("its equal");
}

console.log(num.toString(36)); //its equal

why is that?

dn70a
  • 73
  • 2
  • 8
  • Those numbers are treated by JavaScript as floats; see [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). JavaScript has lately gained [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) support; try `let num = 9999999999999999999999999999999999n` etc. (notice `n` at the end) instead. – Amadan Jan 21 '22 at 03:43
  • This is expected because 9999999999999999999999999999999999 is much larger than the largest safe integer (`Number.MAX_SAFE_INTEGER`) of 9007199254740991. – coreyward Jan 21 '22 at 03:45
  • @coreyward, in addition to this comment, both the `num` and `9999999999999999992999999999999999 ` are converted to `9999999999999999455752309870428160n` if we parse these numbers to bigint. So, when we compare them it comes out to be true. if you do this (num === 999999939999999999999999999999999), it comes out to be false. When you do deal with large numbers, its good to convert them to string and do the computation for precision. – Apoorva Chikara Jan 21 '22 at 03:47

0 Answers0