Integers beyond MAX_SAFE_INTEGER in JavaScript
Intermediate · 4 min read
Order numbers, tweet ids and bank references are often long numbers, 16 to 19 digits. Read one of them into JavaScript as an ordinary number and the last digit can change without any error. Two different records end up with the same id, and the bug looks like a duplicate in the database.
In this tutorial you will find the exact point where JavaScript numbers stop counting by ones, see an id lose its last digit through parseInt and JSON.parse, and then keep every digit with BigInt. You will also see the two places BigInt refuses to cooperate, and why that is a good thing. You need to know try...catch and what JSON is.
Why whole numbers have a limit
A JavaScript number is a double: 64 bits that hold a sign, a size and the digits. The digits get 53 bits in all. With 53 bits you can count every whole number up to 2 ** 53 - 1, which is 9007199254740991. JavaScript names that limit Number.MAX_SAFE_INTEGER.
Past it, the number can still be stored, but there aren't enough digit bits left to tell neighbors apart. First only even numbers exist, then only multiples of 4, and so on.
What "safe" means
A safe integer is a whole number that has its own exact double and is not shared with a neighbor. Every whole number from -9007199254740991 to 9007199254740991 is safe.
Here is the exercise. If you want to try it on your own first, go ahead. Otherwise, read on and we will build it together.
88 Where MAX_SAFE_INTEGER stops being a suggestion
fairShow that 2 ** 53 and 2 ** 53 + 1 are the same number, that the literal 9007199254740993 cannot be written at all, and that reading a 16-digit id out of text or JSON loses its last digit. Then do the same arithmetic with BigInt and see what mixing the two does.
Stuck? Three hints, smallest first
- 1.
Number.MAX_SAFE_INTEGERis2 ** 53 - 1. Above it, only even integers exist for a while. - 2.
Number.isIntegerandNumber.isSafeIntegerdisagree, and the second is the one you want. - 3. A BigInt has to be read back with
String:JSON.stringifythrows on one.
Step 1: the limit
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MAX_SAFE_INTEGER === 2 ** 53 - 1); // true
Step 2: adding 1 stops working
console.log(2 ** 53 === 2 ** 53 + 1); // true
console.log(2 ** 53 + 2 === 2 ** 53 + 1); // false
2 ** 53 + 1 can't be stored, so it is rounded back down to 2 ** 53. Adding 2 still works, because 2 ** 53 + 2 is even and has its own double.
Step 3: a number you can't even write
console.log(9007199254740993); // 9007199254740992
console.log(9007199254740993 === 9007199254740992); // true
You typed one number and JavaScript stored a different one, before any math happened.
Step 4: isInteger versus isSafeInteger
console.log(Number.isInteger(2 ** 53)); // true
console.log(Number.isSafeInteger(2 ** 53)); // false
console.log(Number.isSafeInteger(2 ** 53 - 1)); // true
2 ** 53 really is a whole number, so isInteger says yes. But it is not safe, because 2 ** 53 + 1 lands on it too. When you need to know whether a value can be trusted digit for digit, isSafeInteger is the check you want.
Step 5: losing a digit from text and JSON
console.log(parseInt('9007199254740993')); // 9007199254740992
console.log(JSON.parse('{"id":9007199254740993}').id); // 9007199254740992
console.log(JSON.parse('{"id":"9007199254740993"}').id); // 9007199254740993
Every route from text to a number rounds: parseInt, Number and JSON.parse. None of them warns you. The last line is the fix: if the id travels as a JSON string (in quotes), it stays a string and keeps every digit. Ids are labels, not amounts, so they rarely need to be numbers anyway.
Step 6: BigInt
BigInt is a second number type for whole numbers of any size. Write one with an n at the end, or build one from text with BigInt('...').
console.log(String(BigInt('9007199254740993'))); // 9007199254740993
console.log(String(9007199254740993n + 2n)); // 9007199254740995
console.log(String(2n ** 64n)); // 18446744073709551616
Every digit is kept. String turns a BigInt into plain text for printing.
Step 7: where BigInt says no
const mixError = () => {
try {
return 1n + 1;
} catch (error) {
return error.constructor.name;
}
};
const stringifyError = () => {
try {
return JSON.stringify({ id: 1n });
} catch (error) {
return error.constructor.name;
}
};
console.log(mixError(), stringifyError()); // TypeError TypeError
1n + 1 throws a TypeError. JavaScript refuses to mix a BigInt and a normal number, because one of them would have to be converted and could lose digits. JSON.stringify also throws on a BigInt, rather than writing a number that the other end might round. Both errors protect you. To send a BigInt as JSON, turn it into a string first.
Step 8: far above, only Infinity
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MAX_VALUE * 2 === Infinity); // true
Number.MAX_VALUE is the biggest double there is. Go past it and you get Infinity, again with no error.
The full solution
The answer panel has mixError and stringifyError, and prints the safe limit, the lost digits through a literal, parseInt and JSON, the BigInt results and the overflow to Infinity. Press Run to see the output.
const mixError = () => {
try {
return 1n + 1;
} catch (error) {
return error.constructor.name;
}
};
const stringifyError = () => {
try {
return JSON.stringify({ id: 1n });
} catch (error) {
return error.constructor.name;
}
};
console.log('MAX_SAFE_INTEGER :', Number.MAX_SAFE_INTEGER, '= 2 ** 53 - 1:', Number.MAX_SAFE_INTEGER === 2 ** 53 - 1);
console.log('2 ** 53 + 1 :', 2 ** 53 + 1, 'same as 2 ** 53?', 2 ** 53 === 2 ** 53 + 1);
console.log('the literal :', 9007199254740993);
console.log('isInteger vs safe :', Number.isInteger(2 ** 53), Number.isSafeInteger(2 ** 53));
console.log('parseInt of an id :', parseInt('9007199254740993'));
console.log('through JSON :', JSON.parse('{"id":9007199254740993}').id);
console.log('as a JSON string :', JSON.parse('{"id":"9007199254740993"}').id);
console.log('BigInt :', String(9007199254740993n + 2n), String(2n ** 64n));
console.log('1n + 1 :', mixError(), 'JSON.stringify(1n):', stringifyError());
console.log('past MAX_VALUE :', Number.MAX_VALUE * 2);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('MAX_SAFE_INTEGER is 2 ** 53 - 1, the last integer with a neighbour', [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER === 2 ** 53 - 1], [9007199254740991, true]);
test('one step past it, adding 1 does nothing, but adding 2 still works', [2 ** 53 === 2 ** 53 + 1, 2 ** 53 + 2 === 2 ** 53 + 1], [true, false]);
test('so the literal 9007199254740993 cannot even be written down', [9007199254740993, 9007199254740993 === 9007199254740992], [9007199254740992, true]);
test('isSafeInteger draws the line where isInteger will not', [Number.isSafeInteger(2 ** 53 - 1), Number.isSafeInteger(2 ** 53), Number.isInteger(2 ** 53)], [true, false, true]);
test('parsing a 16-digit id from text quietly loses the last digit', [parseInt('9007199254740993'), String(BigInt('9007199254740993'))], [9007199254740992, '9007199254740993']);
test('a JSON round trip loses it too, unless the id travelled as a string', [JSON.parse('{"id":9007199254740993}').id, JSON.parse('{"id":"9007199254740993"}').id], [9007199254740992, '9007199254740993']);
test('BigInt keeps every digit, and is read back with String', [String(9007199254740993n + 2n), String(2n ** 64n)], ['9007199254740995', '18446744073709551616']);
test('mixing a BigInt with a Number throws, and JSON refuses one outright', [mixError(), stringifyError()], ['TypeError', 'TypeError']);
test('and far above all this there is only Infinity, still with no error', [Number.MAX_VALUE * 2 === Infinity, Number.MAX_VALUE], [true, 1.7976931348623157e+308]);
A double has 53 bits of significand, so every integer up to 2 ** 53 - 1 has an exact representation and a distinct neighbour. Past that, the spacing becomes 2, then 4, then 8. 2 ** 53 + 1 rounds back down to 2 ** 53, which is why 2 ** 53 === 2 ** 53 + 1 is true while 2 ** 53 + 2 is a different number. Number.isInteger(2 ** 53) is also true — it is an integer, just not a safe one — so isSafeInteger is the check that means what you want.
The practical damage is in ids. Snowflake ids, database bigints and payment references routinely run to 17 or 19 digits, and every route into JavaScript rounds them: the literal, parseInt, Number, and JSON.parse. Nothing warns. Two different records can arrive with the same id and the bug looks like a duplicate in the database. The fix is at the boundary: send the id as a JSON string, and keep it a string or a BigInt.
BigInt is exact and deliberately unfriendly about it. 1n + 1 is a TypeError rather than a silent widening, and JSON.stringify throws on a BigInt instead of writing a number it cannot read back. Both refusals are on your side. It also means every assertion about a BigInt in this course goes through String, because the test helper compares with JSON.stringify.
Common mistakes
- Storing long ids as numbers. Anything past 16 digits can change. Keep ids as strings.
- Checking with
Number.isInteger. It says yes to unsafe values like 2 ** 53. UseNumber.isSafeInteger. - Mixing BigInt and Number.
1n + 1throws. Convert one side on purpose:1n + BigInt(1).
Try it yourself
- Start a loop at
Number.MAX_SAFE_INTEGER - 5, count up by 1, and stop whenn + 1 === n. Which number do you stop on? - Write
parseId(text)that returns a BigInt when the text is too big to be safe and a normal number otherwise. - Parse
'{"total":12345678901234567890}'withJSON.parseand print the total. How many digits survived?