BigInt & Number Precision
Published by Brayan K
BigInt is a numeric type for integers of arbitrary size — written with an n suffix like 10n — that stays exact beyond Number.MAX_SAFE_INTEGER, where ordinary floating-point numbers start to round.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Preserve the digits before choosing an integer representation
BigInt can preserve an integer exactly, but it cannot recover digits that were already rounded in a Number. The source representation matters: use a BigInt literal or validate a decimal string before conversion when the exact large integer is available that way.
// The Number literal loses precision before any later conversion.
const rounded = 9007199254740993;
const exact = 9007199254740993n;
console.log(String(rounded));
console.log(String(BigInt(rounded)));
console.log(String(exact));
console.log(String(BigInt("9007199254740993")));
console.log(Number.isSafeInteger(rounded));
// ✅ Expected output:
// 9007199254740992
// 9007199254740992
// 9007199254740993
// 9007199254740993
// falseThe largest safe integer Number is 9007199254740991. “Safe” means adjacent integer values remain distinguishable, not that every larger integer is unrepresentable. For example, some larger even values are exactly representable while nearby odd values round to them. Numbers & Math owns general floating-point behavior; this lesson owns exact integer boundaries and conversions.
console.log(typeof 12n, typeof 12);
console.log(12n === 12, 12n == 12);
console.log(12n < 12.5, 13n > 12.5);
console.log(Boolean(0n), Boolean(1n));
// ✅ Expected output:
// bigint number
// false true
// true true
// false trueStrict equality keeps Number and BigInt distinct. Relational comparisons can compare them, but mixing them in most arithmetic operations is rejected. An API should state which representation it accepts instead of silently changing types according to the current magnitude.
Integer arithmetic has integer results
for (const value of [7n, -7n]) {
const quotient = value / 3n;
const remainder = value % 3n;
console.log(String(quotient), String(remainder));
console.log(quotient * 3n + remainder === value);
}
// ✅ Expected output:
// 2 1
// true
// -2 -1
// trueBigInt does not store a fractional part. Negative division truncates toward zero rather than taking the mathematical floor. The remainder operator is not a universally non-negative modulo operation. If your contract needs a remainder in a positive interval, normalize it deliberately.
const value = -7n, modulus = 3n;
console.log(String(value % modulus));
console.log(String(((value % modulus) + modulus) % modulus));
// ✅ Expected output:
// -1
// 2console.log(2n + 1);
// ✅ Expected error:
// TypeError: Cannot mix BigInt and other types, use explicit conversionsconsole.log(BigInt(1.5));
// ✅ Expected error:
// RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integerconsole.log(1n / 0n);
// ✅ Expected error:
// RangeError: Division by zeroAdding an n suffix does not create a decimal type. To represent hundredths exactly, keep an integer count of hundredths and define how input decimals are parsed. Rounding, exchange rates and arithmetic overflow policies belong to the application contract; they are not supplied by BigInt.
Stay in the intended type when sorting or using numeric tools
const values = [20n, 3n, 100n];
console.log(values.toSorted().map(String).join(", "));
console.log(values.toSorted((a, b) => a < b ? -1 : a > b ? 1 : 0).map(String).join(", "));
// ✅ Expected output:
// 100, 20, 3
// 3, 20, 100console.log(Math.max(2n, 7n));
// ✅ Expected error:
// TypeError: Cannot convert a BigInt value to a numberThe default array sort compares string representations. Subtracting two BigInts produces a BigInt, whereas the comparator result is converted to Number by the sort operation and rejects a BigInt result. A comparison-based comparator returns the small Number signs directly. Math functions operate on Numbers; define a small comparison loop if you need a BigInt maximum.
function toSafeNumber(value) {
if (typeof value !== "bigint") throw new TypeError("bigint required");
if (value < BigInt(Number.MIN_SAFE_INTEGER) || value > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new RangeError("outside safe integer range");
}
return Number(value);
}
console.log(toSafeNumber(42n));
try { toSafeNumber(9007199254740993n); }
catch (error) { console.log(error.name, error.message); }
console.log(String(Number(9007199254740993n)));
// ✅ Expected output:
// 42
// RangeError outside safe integer range
// 9007199254740992A conversion may succeed while losing precision. Rejecting values outside a documented safe range avoids that ambiguity at a Number-only boundary. It is different from accepting every representable but unsafe large Number.
Serialization and fixed-width wrapping need explicit contracts
const original = 9007199254740993n;
try { JSON.stringify({ id: original }); }
catch (error) { console.log(error.name); }
const text = JSON.stringify({ id: String(original) });
const parsed = JSON.parse(text);
console.log(text);
console.log(BigInt(parsed.id) === original);
// ✅ Expected output:
// TypeError
// {"id":"9007199254740993"}
// trueJSON has no BigInt type. This example uses a known field whose decimal-string meaning is defined by the application. A generic reviver that converts every digit-only string would also change postal codes or display labels. Validate the field’s syntax and size before conversion. Deep Dive into JSON, Parsing & Serialization owns schema and serialization boundaries.
console.log(String(BigInt.asUintN(8, 258n)));
console.log(String(BigInt.asIntN(8, 255n)));
console.log(String(BigInt.asUintN(8, -1n)));
// ✅ Expected output:
// 2
// -1
// 255These operations keep the low bits and interpret the result as unsigned or signed. Use them when a binary protocol explicitly requires wrapping. If your requirement is “reject values outside 0–255,” check that range first; wrapping 258 to 2 would silently change the requested value. BigInt arithmetic is not guaranteed to take constant time and is not a drop-in cryptographic implementation.
Guided exercise: count exact whole and fractional units
The input is already split and validated for this short exercise. Fill the literal hints to represent twelve units and five hundredths as one exact integer count. The brief adds actual input validation.
const whole = ___("12"); // 👉 replace ___ with BigInt
const fraction = BigInt("05");
const units = whole * ___ + fraction; // 👉 replace ___ with 100n
console.log(___(units)); // 👉 replace ___ with String
console.log(String(units / 100n), String(units % 100n));
// ✅ Expected output:
// 1205
// 12 5Brief: parse and format an exact two-place decimal
Write parseUnits(text) and formatUnits(units). Accept an optional leading minus, a whole part of 1–30 decimal digits with no leading zero except zero itself, and an optional decimal point followed by one or two digits. Reject spaces, a plus sign, exponents, a trailing newline, an empty fraction and extra fractional digits. Parse directly from strings to BigInt hundredths; never pass through Number.
The formatter accepts only BigInt, rejects magnitudes at or above 10 to the power 32 hundredths, and always writes exactly two fractional digits. Normalize every negative-zero input to "0.00". Parsing a valid formatted result must reproduce the exact integer. Wrong input types throw TypeError; invalid syntax or range throws RangeError with the checked messages. The size limit bounds accepted input and is an application choice.
function parseUnits(text) {
if (typeof text !== "string") throw new TypeError("amount must be a string");
const match = /^(-?)(0|[1-9][0-9]{0,29})(?:\.([0-9]{1,2}))?$/.exec(text);
if (!match || match[0] !== text) throw new RangeError("invalid decimal amount");
const magnitude = BigInt(match[2]) * 100n + BigInt((match[3] ?? "").padEnd(2, "0"));
return match[1] === "-" ? -magnitude : magnitude;
}
function formatUnits(units) {
if (typeof units !== "bigint") throw new TypeError("units must be bigint");
const negative = units < 0n;
const magnitude = negative ? -units : units;
if (magnitude >= 10n ** 32n) throw new RangeError("amount out of range");
return (negative ? "-" : "") + String(magnitude / 100n) + "." +
String(magnitude % 100n).padStart(2, "0");
}
for (const text of ["12.5", "-0.05", "-0.00", "9007199254740993.27"]) {
const value = parseUnits(text);
const formatted = formatUnits(value);
console.log(text, String(value), formatted, parseUnits(formatted) === value);
}
for (const text of ["01", "1.", "1.234", "1e3", "1\n"]) {
try { parseUnits(text); }
catch (error) { console.log(JSON.stringify(text), error.name, error.message); }
}
// ✅ Expected output:
// 12.5 1250 12.50 true
// -0.05 -5 -0.05 true
// -0.00 0 0.00 true
// 9007199254740993.27 900719925474099327 9007199254740993.27 true
// "01" RangeError invalid decimal amount
// "1." RangeError invalid decimal amount
// "1.234" RangeError invalid decimal amount
// "1e3" RangeError invalid decimal amount
// "1\n" RangeError invalid decimal amountThis codec specifies representation and validation. It does not implement rounding to a chosen business rule, percentage calculations, locale input or currency conversion. Those decisions should be explicit before extending it.
Practice quiz
What does this complete program print? console.log(String(BigInt("9007199254740993")));
- 9007199254740993
- 9007199254740992
- 9007199254740993n
- RangeError
Answer: 9007199254740993. The decimal string is converted without a prior Number rounding step.
What does this complete program print? console.log(typeof 2n, 2n === 2);
- number true
- bigint false
- bigint true
- number false
Answer: bigint false. BigInt is distinct from Number under strict equality.
What does this complete program print? console.log(String(-7n / 3n), String(-7n % 3n));
- -3 2
- -2 1
- -2 -1
- -3 -1
Answer: -2 -1. Division truncates toward zero and the remainder keeps the dividend sign.
What does this complete program print? console.log(3n < 3.5, 4n > 3.5);
- false true
- true false
- TypeError
- true true
Answer: true true. Relational comparison supports mixed Number and BigInt values.
What does this complete program print? console.log(String(BigInt.asUintN(8, 257n)));
- 1
- 257
- -1
- RangeError
Answer: 1. Eight-bit wrapping keeps the low bits; it is not a range check.
What does this complete program print? console.log(JSON.stringify({ id: String(12n) }));
- {"id":12}
- {"id":"12"}
- {"id":"12n"}
- TypeError
Answer: {"id":"12"}. An explicit decimal-string field is representable in JSON.
What does this complete program print? console.log([10n, 2n].toSorted((a,b) => a < b ? -1 : a > b ? 1 : 0).map(String).join(","));
- 10,2
- 2n,10n
- 2,10
- TypeError
Answer: 2,10. The comparison produces Number signs for a numeric ordering.
What does this complete program print? console.log(String(BigInt(9007199254740993)));
- 9007199254740993
- 9007199254740993n
- RangeError
- 9007199254740992
Answer: 9007199254740992. The Number literal was rounded before BigInt receives it.
Continue this course
- Previous: Proxy & Reflect (Metaprogramming)
- Next: Checkpoint: Modern JavaScript — Combine modern syntax, methods and a Proxy in a build — then a quiz
- Quick reference: JavaScript cheat sheet