3

Whenever I run this, the number returned gets incremented, can anyone explain this to me?

let array = [9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 1]
return Number(array.join(''))

Outputs:

9223372036854772
philipxy
  • 14,867
  • 6
  • 39
  • 83
jojo oresanya
  • 59
  • 1
  • 1
  • 5
  • 1
    See this [ref](https://stackoverflow.com/questions/8104391/why-do-javascript-converts-some-number-values-automatically) – Daniel A R F Jun 22 '20 at 23:17

2 Answers2

9

The number is larger than Number.MAX_SAFE_INTEGER (253-1). You may want to use BigInt instead.

Example:

let array = [9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 1]
let num = BigInt(array.join(''));
console.log(num.toString());
console.log("Doubled:", (num * 2n).toString());
console.log("Squared:", (num ** 2n).toString());

You can use Number.isSafeInteger to check if a value is precise.

let array = [9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 1]
let num = Number(array.join(''));
console.log("Safe?", Number.isSafeInteger(num));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

The result of array.join('') is "9223372036854772". That is much larger than Number.MAX_SAFE_INTEGER. Number constructor can't precisely hold numbers greater than Number.MAX_SAFE_INTEGER, and therefore you get this error. You might want to use something like a BigInt for handling such large numbers.

acagastya
  • 323
  • 2
  • 14