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,416
  • 5
  • 32
  • 77
jojo oresanya
  • 59
  • 1
  • 5

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
  • 46,070
  • 7
  • 44
  • 60
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
  • 303
  • 2
  • 13