jojo oresanya
jojo oresanya

Reputation: 59

Why does the Number() method increment the value of a number when the length of the number is greater than 15?

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

Upvotes: 3

Views: 123

Answers (2)

acagastya
acagastya

Reputation: 393

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.

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89374

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));

Upvotes: 9

Related Questions