Safe Integers Bound Numeric Precision

Integers beyond 2^53 lose exactness, so Number.isSafeInteger guards both inputs and results before IDs or amounts enter arithmetic.

JavascriptData Integrity

Code

javascriptsnippet
28 lines
// 2^53 - 1 是 Number 能精确表示的最大整数
console.log('MAX_SAFE_INTEGER:', Number.MAX_SAFE_INTEGER);
console.log('isSafeInteger(2**53-1):', Number.isSafeInteger(2 ** 53 - 1));
console.log('isSafeInteger(2**53):', Number.isSafeInteger(2 ** 53));

// 越界后相邻整数坍缩:+1 得到的还是同一个数,只有偶数间隔可区分
console.log('2**53:', 2 ** 53);
console.log('2**53 + 1 === 2**53:', 2 ** 53 + 1 === 2 ** 53);
console.log('2**53 + 2 distinct:', 2 ** 53 + 2 !== 2 ** 53 + 1);

// 实务护栏:ID/金额相加前校验输入,相加后还要校验结果
function addIds(a, b) {
  if (!Number.isSafeInteger(a) || !Number.isSafeInteger(b)) {
    throw new RangeError('input outside safe range');
  }
  const sum = a + b;
  if (!Number.isSafeInteger(sum)) {
    throw new RangeError('sum exceeds safe range');
  }
  return sum;
}

console.log('add ok:', addIds(Number.MAX_SAFE_INTEGER - 2, 2));
try {
  addIds(Number.MAX_SAFE_INTEGER, 1); // 输入都安全,但和值越界
} catch (error) {
  console.log('rejected:', error.name, error.message);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

MAX_SAFE_INTEGER: 9007199254740991
isSafeInteger(2**53-1): true
isSafeInteger(2**53): false
2**53: 9007199254740992
2**53 + 1 === 2**53: true
2**53 + 2 distinct: true
add ok: 9007199254740991
rejected: RangeError sum exceeds safe range

The boundary value

Number.MAX_SAFE_INTEGER is 2^53 - 1. isSafeInteger(253-1) prints true while isSafeInteger(253) prints false — one past the line is already unsafe.

Collapsed neighbors

Above 2^53 adjacent integers merge: 253 + 1 === 253 prints true, while +2 is still distinguishable (2**53 + 2 distinct: true). Only every other integer is representable in that region.

Guarding arithmetic

addIds validates both inputs and the sum with Number.isSafeInteger, throwing RangeError on either side. The demo shows an accepted addition (MAX_SAFE_INTEGER - 2 + 2) and a rejected one (MAX_SAFE_INTEGER + 1) whose inputs are individually safe but whose sum is not.

Interactive Tools for This Topic

FAQ

Why do integers above 2^53 lose exactness?
IEEE 754 doubles carry 53 bits of mantissa; beyond that, adjacent integers cannot all be represented and neighbors collapse to the same value.
What does addIds guard against?
It checks both inputs and the resulting sum with Number.isSafeInteger and throws RangeError when either side is outside the safe range.