简体   繁体   中英

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

The number is larger than Number.MAX_SAFE_INTEGER (2 53 -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));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM