How to work with very large integers
Short answer
Ordinary numbers are exact only up to 2 to the power 53. For larger integers, use BigInt, which is written with the n suffix:
console.log(9007199254740993);
console.log(String(9007199254740993n));Output:
9007199254740992
9007199254740993Calculations
BigInt numbers support the usual operators, but both operands must be BigInt:
const big = 2n ** 64n;
console.log(big.toString());
console.log((big / 3n).toString());Output:
18446744073709551616
6148914691236517205From a string
Large ids often come as strings. BigInt() turns them into numbers without losing digits:
const id = BigInt('123456789012345678901');
console.log((id + 1n).toString());Output:
123456789012345678902Common mistake
You cannot mix BigInt and ordinary numbers in one operation. Convert one of them explicitly:
try {
console.log(10n + 1);
} catch (error) {
console.log(error.message);
}
console.log((10n + BigInt(1)).toString());Output:
Cannot mix BigInt and other types, use explicit conversions
11Functions used in this recipe
- BigInt — Integers of any size, without loss of precision.
- Number.MAX_SAFE_INTEGER — The largest integer that is stored without losing precision.