Codectionary / Developer documentation / JavaScript

Exact Integer Arithmetic with BigInt

BigInt represents integers beyond Number’s safe integer range. Create values with an n suffix or BigInt from an integer string. Arithmetic generally cannot mix Number and BigInt; integer division truncates toward zero. BigInt is standardized in ES2020 and cannot be directly JSON-stringified.

Syntax

const value = 9007199254740993n;
const parsed = BigInt("9007199254740993");

Examples

Exact Integer Arithmetic with BigInt: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: Logs are 9007199254740995, 3, and {"balance":"9007199254740993"}.

const balance = BigInt("9007199254740993");
console.log((balance + 2n).toString());
console.log((7n / 2n).toString());
console.log(JSON.stringify({ balance: balance.toString() }));
  1. Expected result: Logs are 9007199254740995, 3, and {"balance":"9007199254740993"}.
  2. Parsing a string avoids rounding through an intermediate Number.
  3. Serializing as a decimal string preserves the integer but requires an agreed decoding convention.

Best practices

  • Keep units and numeric types consistent through calculations.
  • Check range before converting a BigInt back to Number.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading