Sub topic 6
The Safe Integer Range
This chapter assumes you know how JavaScript stores a Number as a 64-bit IEEE 754 double. You should also be comfortable with ===, typeof, and running code in Node.js or a browser console. Earlier chapters showed that fractions such as 0.1 get rounded. This chapter shows that large whole numbers get rounded too, and explains where that starts.
Where the Limit Comes From
A double has 52 stored fraction bits. Normalized numbers also carry an implicit leading 1, so the significand holds 53 bits of precision. Any integer whose magnitude fits in 53 bits can be stored exactly. Above that, the exponent keeps growing, but the significand has no spare bits for the ones place. The number line then starts skipping integers.
JavaScript exposes the boundary as two constants:
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.MAX_SAFE_INTEGER === 2 ** 53 - 1); // true
console.log(Number.MIN_SAFE_INTEGER === -(2 ** 53 - 1)); // trueWhat "safe" means exactly
An integer n is safe if it is represented exactly and no other integer rounds to the same double. The value 2^53 is stored exactly, yet it is not safe, because 2^53 + 1 rounds to it. You cannot tell which of the two integers you started with.
console.log(2 ** 53 === 2 ** 53 + 1); // true
console.log(9007199254740993); // 9007199254740992
console.log(Number.isInteger(2 ** 53)); // true
console.log(Number.isSafeInteger(2 ** 53)); // false
console.log(Number.isSafeInteger(2 ** 53 - 1)); // trueNumber.isInteger asks whether the stored value has no fractional part. Number.isSafeInteger asks the stricter question of whether you can trust that value. The validation chapter covers both methods alongside the other Number.is* checks.
How the Gaps Grow
Each time the magnitude doubles, the distance between neighbouring doubles also doubles.
| Magnitude range | Gap between adjacent doubles | Every integer representable? |
|---|---|---|
| [1, 2) | 2^-52 (`Number.EPSILON`) | Yes, with fractions |
| [2^52, 2^53) | 1 | Yes, no fractions left |
| [2^53, 2^54) | 2 | Only even integers |
| [2^54, 2^55) | 4 | Only multiples of 4 |
| near 1e21 | 131072 | Very sparse |
| near `Number.MAX_VALUE` (~1.8e308) | ~2e292 | Extremely sparse |
Number.EPSILON is the gap at 1, and the safe-integer limit is where the gap reaches 2. Both come from the same 53-bit significand.
Results that land between two representable values round to the nearest one. A tie goes to the neighbour with an even significand. This explains some results that look odd at first:
console.log(2 ** 53 + 2); // 9007199254740994 (representable)
console.log(2 ** 53 + 3); // 9007199254740996 (tie, rounds to even significand)
console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992 (not ...993)
console.log(2 ** 54 + 1 === 2 ** 54); // true
console.log(2 ** 54 + 2 === 2 ** 54); // true (tie, rounds down to even)
console.log(2 ** 54 + 4 === 2 ** 54); // falseCommon Failure Modes
Large IDs in JSON
This is the most common real-world bug in this area. Databases and APIs often use 64-bit integer IDs. JSON.parse turns every numeric token into a Number, so it rounds large IDs without any warning:
const payload = '{"id": 9007199254740993, "idStr": "9007199254740993"}';
const data = JSON.parse(payload);
console.log(data.id); // 9007199254740992 (wrong ID)
console.log(data.idStr); // "9007199254740993"
console.log(BigInt(data.idStr)); // 9007199254740993nThe usual fix is for the server to send large IDs as strings. Many public APIs do this, for example with a parallel id_str field. Keep IDs as strings on the client unless you need to do arithmetic on them. If you do need arithmetic, convert them to BigInt, which the final chapter covers. Never parse an ID with Number() or parseInt "just to be sure". The precision is already gone when the conversion runs.
Safe inputs, unsafe results
Each operand can be safe while the result is not. The engine does not throw. It rounds:
const a = Number.MAX_SAFE_INTEGER;
console.log(Number.isSafeInteger(a)); // true
console.log(Number.isSafeInteger(a + 1)); // false
console.log(a * 2); // 18014398509481982 (happens to be exact)
console.log(a * 3); // 27021597764222972 (true value ...973)If you need exact integer arithmetic on Numbers, check the inputs and the result:
function safeAdd(a, b) {
const result = a + b;
if (!Number.isSafeInteger(a) || !Number.isSafeInteger(b) || !Number.isSafeInteger(result)) {
throw new RangeError(`Unsafe integer arithmetic: ${a} + ${b}`);
}
return result;
}
console.log(safeAdd(1, 2)); // 3
try {
safeAdd(Number.MAX_SAFE_INTEGER, 1);
} catch (e) {
console.log(e.message); // Unsafe integer arithmetic: 9007199254740991 + 1
}This check is sound for addition, subtraction, and multiplication of safe integers. If the exact result is 2^53 or larger in magnitude, the rounded result is too, so a bad result can never pass the check by rounding back into the safe range.
Counters that stop counting
Past 2^53, i++ can return the same value it started with. A loop that relies on it may never end:
let i = 2 ** 53;
const before = i;
i++;
console.log(i === before); // true: the increment was lost
// A loop like this would never terminate:
// for (let n = 2 ** 53; n < 2 ** 53 + 10; n++) { ... }Timestamps at high resolution
Date.now() returns milliseconds since 1970, about 1.7e12, which is far inside the safe range. Microsecond timestamps, about 1.7e15, still fit. Nanosecond timestamps, about 1.7e18, do not. In Node.js, process.hrtime.bigint() exists because a nanosecond clock cannot be a safe Number.
const ms = Date.now();
console.log(Number.isSafeInteger(ms)); // true
console.log(Number.isSafeInteger(ms * 1000)); // true (microseconds)
console.log(Number.isSafeInteger(ms * 1e6)); // false (nanoseconds)Other places where integers get smaller
Some operations limit integers more tightly than 2^53. Bitwise operators convert their operands to 32-bit signed integers, as a later chapter explains. Array lengths and indexes are limited to 2^32 - 1. Typed arrays such as Int32Array wrap values to their element width. Being safe as a Number does not mean a value is safe everywhere.
Choosing a Strategy
| Situation | Recommended approach |
|---|---|
| Counts, prices in cents, ms timestamps | Plain Number, which stays far below 2^53 |
| Opaque IDs from external systems | Strings |
| Exact arithmetic that may exceed 2^53 | BigInt |
| Untrusted numeric input meant to be an integer | Validate with `Number.isSafeInteger` |
| Scientific magnitudes where approximation is fine | Plain Number, accepting rounding |
The deciding question is whether you need every integer to be distinct and exact. If you do, stay below 2^53 or switch to BigInt or strings. If an approximation is acceptable, as in physics or statistics, values past 2^53 are fine as Numbers.
Exercise
Without running it, predict the output of console.log(9007199254740995, Number.isSafeInteger(9007199254740990 + 1)), and explain each value.
Show answer
It prints 9007199254740996 true. The literal 9007199254740995 lies between the representable even neighbours ...994 and ...996, at exactly the midpoint. Round-half-to-even picks ...996, whose significand is even. The sum 9007199254740990 + 1 is 9007199254740991, which equals Number.MAXSAFEINTEGER, so it is safe.
Exercise
An API returns {"orderId": 12345678901234567}. Your code does const id = JSON.parse(body).orderId; and later looks the order up by id. What goes wrong, and how should it be fixed?
Show answer
12345678901234567 is above 2^53 (about 9.007e15), so JSON.parse rounds it to the nearest double, 12345678901234568. The lookup then uses the wrong ID. Checking afterwards cannot fix this, because the precision is already gone. The API should send the ID as a JSON string, and the client should keep it as a string, or convert it with BigInt(idString) if arithmetic is needed. Checking Number.isSafeInteger(id) can detect the problem, but it cannot recover the original value.