BigInt
suggest changeBigInt is a built-in JavaScript type for integers of arbitrary size. It's been available in every Node.js version since 10.4, needs no import and no npm package.
You need it because the regular number type is a 64-bit float. It represents integers exactly only up to 253 - 1:
console.log(Number.MAX_SAFE_INTEGER);
console.log(2 ** 53 + 1);
console.log(9007199254740993 === 9007199254740992);
console.log(BigInt(Number.MAX_SAFE_INTEGER) + 2n);
console.log(2n ** 64n);
9007199254740991
9007199254740992
true
9007199254740993n
18446744073709551616n
Typical places where you hit this limit in Node.js:
- 64-bit IDs from databases (
BIGINTcolumns), Twitter/Discord snowflake IDs - 64-bit integers in binary file formats and network protocols
- nanosecond timestamps (
process.hrtime.bigint(),fs.stat()withbigint: true) - cryptography and hashing math (modular exponentiation, 64-bit hashes)
- money amounts stored as integer cents that must never be rounded
Creating BigInt values
Append n to an integer literal or call BigInt() as a function:
console.log(123n);
console.log(1_000_000n); // numeric separators work
console.log(0xffn, 0b1010n, 0o17n); // hex, binary, octal literals
console.log(BigInt(42));
console.log(BigInt('12345678901234567890'));
console.log(BigInt('0xff'), BigInt(' 42 '), BigInt(true));
console.log(typeof 10n);
123n
1000000n
255n 10n 15n
42n
12345678901234567890n
255n 42n 1n
bigint
Always create large values from a string or a literal. BigInt(12345678901234567890) first creates a number, which has already lost precision before BigInt() sees it.
BigInt() is strict about its input:
for (const v of [1.5, '1.5', 'abc', NaN, undefined]) {
try {
console.log(BigInt(v));
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
}
try {
new BigInt(1);
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer
SyntaxError: Cannot convert 1.5 to a BigInt
SyntaxError: Cannot convert abc to a BigInt
RangeError: The number NaN cannot be converted to a BigInt because it is not an integer
TypeError: Cannot convert undefined to a BigInt
TypeError: BigInt is not a constructor
When parsing user input, wrap BigInt() in try/catch, or check the string with a regular expression like /^-?\d+$/ first.
Arithmetic
The usual operators work, as long as both operands are BigInts:
console.log(7n + 3n, 7n - 10n, 7n * 3n);
console.log(7n / 2n, -7n / 2n); // division truncates toward zero
console.log(7n % 3n, -7n % 3n); // remainder takes the sign of the dividend
console.log(2n ** 100n);
10n -3n 21n
3n -3n
1n -1n
1267650600228229401496703205376n
There are no fractions: / drops the remainder. If you need rounding up or to nearest, write it yourself:
const divCeil = (a, b) => (a + b - 1n) / b; // for positive a and b
function divRound(a, b) {
const q = a / b;
const r = a % b;
const abs = (x) => (x < 0n ? -x : x);
if (2n * abs(r) >= abs(b)) {
return q + ((a < 0n) === (b < 0n) ? 1n : -1n);
}
return q;
}
console.log(divCeil(7n, 2n), divRound(7n, 2n), divRound(-7n, 2n), divRound(10n, 3n));
4n 4n -4n 3n
What doesn't work
const tests = {
'mix with number': () => 1n + 1,
'unary plus': () => +1n,
'unsigned shift': () => 1n >>> 0n,
'divide by zero': () => 1n / 0n,
'Math.max': () => Math.max(1n, 2n),
};
for (const [name, fn] of Object.entries(tests)) {
try {
fn();
} catch (e) {
console.log(`${name}: ${e.name}: ${e.message}`);
}
}
mix with number: TypeError: Cannot mix BigInt and other types, use explicit conversions
unary plus: TypeError: Cannot convert a BigInt value to a number
unsigned shift: TypeError: BigInts have no unsigned right shift, use >> instead
divide by zero: RangeError: Division by zero
Math.max: TypeError: Cannot convert a BigInt value to a number
JavaScript refuses to silently mix the two types, because either direction could lose information. Convert explicitly:
const count = 5;
const total = 10n;
console.log(total + BigInt(count)); // stay in BigInt
console.log(Number(total) + count); // or go to number (may lose precision)
15n
15
String concatenation and template literals do work: 'id: ' + 5n is 'id: 5'.
Comparison and equality
Comparison operators work across types, strict equality doesn't:
console.log(1n == 1); // true
console.log(1n === 1); // false: different types
console.log(2n > 1); // true
console.log(1n < 1.5); // true
console.log(Boolean(0n), Boolean(1n)); // 0n is falsy like 0
true
false
true
true
false true
This matters for collections, which use strict equality (SameValueZero):
const m = new Map([[1n, 'a']]);
console.log(m.get(1n), m.get(1));
console.log(new Set([1n, 1, 1n]).size);
console.log([1n, 2n].includes(1));
a undefined
2
false
Array.prototype.sort() without a comparator sorts by string, which is wrong for numbers of any type. The usual (a, b) => a - b comparator doesn't work either, because sort() expects a number back. Use a comparator that returns -1, 0 or 1:
const ids = [30n, 1n, 200n, 4n];
console.log([...ids].sort());
console.log([...ids].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)));
[ 1n, 200n, 30n, 4n ]
[ 1n, 4n, 30n, 200n ]
Converting to number and string
Number(big) converts but silently rounds values beyond the safe range. When precision matters, check first:
function toSafeNumber(b) {
if (b > BigInt(Number.MAX_SAFE_INTEGER) || b < BigInt(Number.MIN_SAFE_INTEGER)) {
throw new RangeError(`${b} is outside the safe integer range`);
}
return Number(b);
}
console.log(Number(12345678901234567890n));
console.log(toSafeNumber(123n));
try {
toSafeNumber(12345678901234567890n);
} catch (e) {
console.log(e.message);
}
12345678901234567000
123
12345678901234567890 is outside the safe integer range
toString() accepts a radix, and toLocaleString() / Intl.NumberFormat format BigInts directly, without converting to number:
import { inspect } from 'node:util';
const big = 12345678901234567890n;
console.log(big.toString());
console.log(big.toString(16));
console.log((255n).toString(2));
console.log(big.toLocaleString('en-US'));
console.log(big.toLocaleString('de-DE'));
console.log(new Intl.NumberFormat('en-US', { notation: 'compact' }).format(2n ** 70n));
console.log(inspect(2n ** 70n, { numericSeparator: true }));
12345678901234567890
ab54a98ceb1f0ad2
11111111
12,345,678,901,234,567,890
12.345.678.901.234.567.890
1,180,591,621T
1_180_591_620_717_411_303_424n
Bitwise operations and fixed-width integers
&, |, ^, ~, << and >> work on BigInts and, unlike with number, aren't limited to 32 bits:
console.log(0b1100n & 0b1010n, 0b1100n | 0b1010n, 0b1100n ^ 0b1010n);
console.log(~5n, 1n << 70n, -16n >> 2n);
8n 14n 6n
-6n 1180591620717411303424n -4n
BigInts never overflow; they just grow. To emulate C-style 64-bit (or any width) integers, wrap results with BigInt.asUintN(bits, n) or BigInt.asIntN(bits, n):
console.log(BigInt.asUintN(64, -1n)); // -1 as uint64
console.log(BigInt.asIntN(64, 2n ** 63n)); // overflow into negative int64
console.log(BigInt.asIntN(8, 255n)); // 255 as int8
console.log(BigInt.asUintN(8, 257n)); // wraps around
18446744073709551615n
-9223372036854775808n
-1n
1n
Here's the 64-bit FNV-1a hash, which needs unsigned 64-bit multiplication with wraparound:
function fnv1a64(str) {
let hash = 0xcbf29ce484222325n;
for (const byte of Buffer.from(str)) {
hash ^= BigInt(byte);
hash = BigInt.asUintN(64, hash * 0x100000001b3n);
}
return hash;
}
console.log(fnv1a64('hello').toString(16));
a430d84680aabd0b
Math helpers
The Math object only works with number. Common replacements are short:
const abs = (n) => (n < 0n ? -n : n);
const max = (...xs) => xs.reduce((a, b) => (b > a ? b : a));
const min = (...xs) => xs.reduce((a, b) => (b < a ? b : a));
function gcd(a, b) {
a = abs(a);
b = abs(b);
while (b) [a, b] = [b, a % b];
return a;
}
// integer square root (floor), Newton's method
function sqrt(n) {
if (n < 0n) throw new RangeError('square root of negative number');
if (n < 2n) return n;
let x = 1n << BigInt(Math.ceil(n.toString(2).length / 2));
while (true) {
const y = (x + n / x) / 2n;
if (y >= x) return x;
x = y;
}
}
// (base ** exp) % mod without building a gigantic intermediate number
function modPow(base, exp, mod) {
let result = 1n;
base %= mod;
while (exp > 0n) {
if (exp & 1n) result = (result * base) % mod;
base = (base * base) % mod;
exp >>= 1n;
}
return result;
}
function factorial(n) {
let r = 1n;
for (let i = 2n; i <= n; i++) r *= i;
return r;
}
console.log(abs(-42n), max(3n, 17n, 5n), min(3n, 17n, 5n), gcd(1071n, 462n));
console.log(sqrt(10n ** 40n), sqrt(99n));
console.log(modPow(2n, 10n ** 18n, 1_000_000_007n));
console.log(factorial(30n));
console.log(factorial(100n).toString().length, 'digits in 100!');
42n 17n 3n 21n
100000000000000000000n 9n
719476260n
265252859812191058636308480000000n
158 digits in 100!
Example: exact money arithmetic
Floating point can't represent most decimal fractions, and for very large amounts it can't even represent every cent. Storing amounts as integer cents in a BigInt is exact at any size:
function toCents(s) {
const m = /^(\d+)(?:\.(\d{1,2}))?$/.exec(s);
if (!m) throw new SyntaxError(`invalid amount: ${s}`);
return BigInt(m[1]) * 100n + BigInt((m[2] ?? '').padEnd(2, '0'));
}
function formatCents(c) {
const sign = c < 0n ? '-' : '';
if (c < 0n) c = -c;
return `${sign}${c / 100n}.${(c % 100n).toString().padStart(2, '0')}`;
}
const total = toCents('19999999999999.99') + toCents('0.02') + toCents('5.5');
console.log(formatCents(total));
console.log(19999999999999.99 + 0.02 + 5.5);
// split $100 three ways without losing a cent
const amount = toCents('100');
const share = amount / 3n;
const rest = amount % 3n;
const shares = [0n, 1n, 2n].map((i) => formatCents(share + (i < rest ? 1n : 0n)));
console.log(shares);
20000000000005.51
20000000000005.508
[ '33.34', '33.33', '33.33' ]
BigInt in Node.js APIs
Binary data: Buffer, DataView and typed arrays
Buffer has methods to read and write 64-bit integers as BigInts:
const buf = Buffer.alloc(16);
buf.writeBigUInt64BE(18446744073709551615n, 0);
buf.writeBigInt64LE(-2n, 8);
console.log(buf);
console.log(buf.readBigUInt64BE(0), buf.readBigInt64BE(0), buf.readBigInt64LE(8));
try {
buf.writeBigUInt64BE(2n ** 64n);
} catch (e) {
console.log(`${e.code}: ${e.message}`);
}
<Buffer ff ff ff ff ff ff ff ff fe ff ff ff ff ff ff ff>
18446744073709551615n -1n -2n
ERR_OUT_OF_RANGE: The value of "value" is out of range. It must be >= 0n and < 2n ** 64n. Received 18_446_744_073_709_551_616n
The standard DataView has getBigInt64 / getBigUint64 / setBigInt64 / setBigUint64, and there are BigInt64Array and BigUint64Array typed arrays:
const view = new DataView(new ArrayBuffer(8));
view.setBigUint64(0, 0x0102030405060708n); // big-endian by default
console.log(view.getBigUint64(0).toString(16));
console.log(view.getBigUint64(0, true).toString(16)); // read as little-endian
const arr = new BigInt64Array([1n, -1n, 2n ** 63n]);
console.log(arr);
console.log(new BigUint64Array(arr.buffer));
102030405060708
807060504030201
BigInt64Array(3) [ 1n, -1n, -9223372036854775808n ]
BigUint64Array(3) [ 1n, 18446744073709551615n, 9223372036854775808n ]
For integers wider than 64 bits, go through a hex string:
const bufferToBigInt = (buf) => BigInt('0x' + (buf.toString('hex') || '0'));
function bigIntToBuffer(n) {
let hex = n.toString(16);
if (hex.length % 2) hex = '0' + hex;
return Buffer.from(hex, 'hex');
}
console.log(bufferToBigInt(Buffer.from([0x00, 0xff, 0x10])));
console.log(bigIntToBuffer(2n ** 64n));
65296n
<Buffer 01 00 00 00 00 00 00 00 00>
See Base64 and hex encoding for more on converting buffers.
High-resolution time
process.hrtime.bigint() returns a monotonic timestamp in nanoseconds:
const start = process.hrtime.bigint();
for (let i = 0; i < 1e6; i++);
const elapsed = process.hrtime.bigint() - start;
console.log(`${elapsed / 1000n} µs`);
console.log(`${Number(elapsed) / 1e6} ms`);
1160 µs
1.1608 ms
Differences between timestamps are small, so converting them to number for display is safe. See Benchmarks for more on measuring time.
File stats with nanosecond precision
Pass { bigint: true } to fs.stat(), fs.lstat() or fs.fstat() and all numeric fields become BigInts, plus you get extra *Ns fields:
import { statSync } from 'node:fs';
const st = statSync('package.json', { bigint: true });
console.log(typeof st.size, st.size);
console.log(st.mtimeNs);
console.log(st.mtimeMs);
bigint 1290n
1792257802503671600n
1792257802503n
SQLite and other databases
The built-in node:sqlite module throws when an integer column doesn't fit in a number. Enable BigInt results per statement with setReadBigInts(true):
import { DatabaseSync } from 'node:sqlite';
const db = new DatabaseSync(':memory:');
db.exec('CREATE TABLE t (id INTEGER PRIMARY KEY, v INTEGER)');
db.prepare('INSERT INTO t (id, v) VALUES (?, ?)').run(1, 9223372036854775807n);
const query = db.prepare('SELECT v FROM t WHERE id = 1');
try {
query.get();
} catch (e) {
console.log(`${e.code}: ${e.message}`);
}
query.setReadBigInts(true);
console.log(query.get());
ERR_OUT_OF_RANGE: Value is too large to be represented as a JavaScript number: 9223372036854775807
[Object: null prototype] { v: 9223372036854775807n }
Other drivers have similar options. For example pg returns BIGINT (int8) columns as strings by default, which you can convert with BigInt() or by registering a type parser with pg.types.setTypeParser().
JSON
JSON.stringify() throws on BigInt values:
try {
JSON.stringify({ id: 1n });
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
const json = JSON.stringify({ id: 12345678901234567890n }, (key, value) =>
typeof value === 'bigint' ? value.toString() : value
);
console.log(json);
TypeError: Do not know how to serialize a BigInt
{"id":"12345678901234567890"}
Sending big integers as strings is the most portable choice, since many JSON parsers in other languages also lose precision on large numbers. For parsing large numbers back into BigInts with JSON.parse() and the reviver's context.source, and for writing unquoted big numbers with JSON.rawJSON(), see JSON.
You'll find advice to add BigInt.prototype.toJSON = function () { return this.toString(); }. It works, but it modifies a global built-in for every module in the process, including your dependencies. Prefer a replacer.
structuredClone(), worker.postMessage() and v8.serialize() support BigInt natively:
console.log(structuredClone({ id: 2n ** 70n }));
{ id: 1180591620717411303424n }
Performance
BigInts are heap-allocated, arbitrary-precision values, so they're much slower than number, which V8 can keep in CPU registers:
function sumNumbers(n) {
let s = 0;
for (let i = 0; i < n; i++) s += i;
return s;
}
function sumBigInts(n) {
let s = 0n;
for (let i = 0n; i < n; i++) s += i;
return s;
}
let t = performance.now();
sumNumbers(10_000_000);
console.log(`number: ${(performance.now() - t).toFixed(0)} ms`);
t = performance.now();
sumBigInts(10_000_000n);
console.log(`bigint: ${(performance.now() - t).toFixed(0)} ms`);
number: 6 ms
bigint: 182 ms
Use number by default and BigInt only for values that can actually exceed 253, such as IDs and 64-bit fields, or for math that must be exact.
Summary of gotchas
- Create large values from literals (
123n) or strings, never from anumberliteral - You can't mix BigInt and
numberin arithmetic; convert explicitly withBigInt()orNumber() 1n === 1isfalse, soMap,Set,includes()andindexOf()treat them as different keys/truncates toward zero; there are no fractional BigIntsMath.*functions, unary+and>>>don't work with BigIntsNumber(big)silently loses precision aboveNumber.MAX_SAFE_INTEGERJSON.stringify()throws; use a replacersort()needs a comparator that returns -1, 0 or 1, nota - b- BigInt is much slower than
number; use it only where you need it