0

Node.js is mutating the number value passed into the test function. Any idea why and how to fix? Thank you!

const val1  = 61368443939717130;
const val2 = 861368443939717130;
const val3 = 161368443939717130;

const test = (v) => {
  console.log(v);
}

test(val1);
test(val2);
test(val3);

// Output:
// 61368443939717130
// 861368443939717100
// 161368443939717120
Dominik
  • 6,078
  • 8
  • 37
  • 61
  • Nothing is being mutated here. You're just hitting the limits of how big a number in JS can be. Look up `bigInt` – Dominik Aug 07 '21 at 23:33
  • Does this answer your question? [What is JavaScript's highest integer value that a number can go to without losing precision?](https://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin) – tevemadar Aug 07 '21 at 23:37

2 Answers2

0

It's because the number 161368443939717130 is bigger than the maximum safe integer that Javascript can represent, which is provided by the constant Number.MAX_SAFE_INTEGER. When working with big numbers you should always check that the values are below the limit, or otherwise you will get unexpected results. See more info here.

chesscov77
  • 770
  • 8
  • 14
0

Your numbers are out of range for javascript.

The max number javascript can handle is 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion).

It is represented by the MAX_SAFE_INTEGER variable. The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integers between -(2^53 - 1) and 2^53 - 1.

Use BigInt, which has no practical upper limit. But BigInt can’t handle decimals. This means that if you convert from a Number to a BigInt and backward again, you can lose precision.

console.log(Number.MAX_SAFE_INTEGER)
// 9007199254740991
console.log(Number.MAX_SAFE_INTEGER + 10)
// 9007199254741000
console.log(BigInt(Number.MAX_SAFE_INTEGER) + 10n) 
// 9007199254741001n
Ridham Tarpara
  • 5,970
  • 4
  • 19
  • 39