Bigint Handles Integers Beyond Safe Range
Use BigInt once integers exceed Number.MAX_SAFE_INTEGER: exact arithmetic, explicit conversions, and a TypeError when mixing the two types.
Code
const limit = Number.MAX_SAFE_INTEGER;
console.log('safe limit:', limit);
// 超出安全区间的 Number 会失真:相邻两个数加出来相等
console.log('number distorts:', limit + 1 === limit + 2);
console.log('bigint exact:', BigInt(limit) + 1n === BigInt(limit) + 2n);
const productId = 9007199254740993n;
console.log('id as number:', Number(productId));
console.log('id as bigint:', productId.toString());
// BigInt 与 Number 不能直接混合运算,先显式转换
try {
1n + 1;
} catch (error) {
console.log('mixing throws TypeError:', error instanceof TypeError);
}
console.log('explicit convert:', 1n + BigInt(1));How it works
Module-level bindings hold the data — limit, productId — with no function scope in between.
Putting it to use
Each run prints the 7 labeled blocks safe limit:, number distorts:, bigint exact:, id as number:, id as bigint:, mixing throws TypeError:, explicit convert: in source order.
Core lines
const limit = Number.MAX_SAFE_INTEGER;
const productId = 9007199254740993n;
Interactive Tools for This Topic
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Roman Numeral ConverterConvert integers between 1 and 3999 to Roman numerals and back, rejecting malformed numeral forms.Scientific Notation ConverterConvert numbers between plain decimal and scientific notation, optionally fixing the significant digits and splitting out the mantissa and exponent.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `limit`, `productId`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.