JavaScript BigInt

BigInt 是 JavaScript 在 ES2020 (ES11) 引入的一種全新原始資料型別 (Primitive Type),它可以用來表示任意長度的整數。

BigInt 出現之前,JavaScript 的 Number 型別使用的是 64 位元浮點數 (IEEE 754),這導致它能精確表示的整數範圍有限。

為什麼需要 BigInt?

JavaScript 的 Number 型別有一個「安全整數範圍」,可以透過 Number.MAX_SAFE_INTEGER 取得,其值為 $2^{53} - 1$ (即 9,007,199,254,740,991)。

一旦超過這個範圍,數值運算就會失去精度:

const max = Number.MAX_SAFE_INTEGER;

console.log(max + 1); // 9007199254740992
console.log(max + 2); // 9007199254740992 (結果錯了,應該要加 1)

BigInt 的出現解決了這個問題,讓開發者可以處理極大的整數(例如高精度的金融計算、大數字的 ID 等)。

如何建立 BigInt

建立 BigInt 有兩種主要方式:

  1. 在整數末尾加上一個小寫的 n
  2. 使用 BigInt() 函式。
// 方式一:加上 n
const hugeInt = 9007199254740991n;

// 方式二:使用 BigInt() 轉換
const alsoHuge = BigInt(9007199254740991);
const fromString = BigInt('9007199254740991000000');

BigInt 的特點與限制

不能與 Number 混用運算

BigIntNumber 是不同的型別。為了避免隱含的精度損失,JavaScript 不允許將兩者直接混合運算。

const big = 10n;
const num = 5;

// 這會報錯:TypeError: Cannot mix BigInt and other types
// console.log(big + num);

// 正確做法:手動轉換
console.log(big + BigInt(num)); // 15n

除法運算會無條件捨去

由於 BigInt 代表的是「整數」,因此在進行除法時,結果會自動捨去小數點後的部分。

const result = 5n / 2n;
console.log(result); // 2n (而非 2.5)

可以與 Number 進行比較

雖然不能混合運算,但 BigIntNumber 之間是可以直接進行大小比較的。

console.log(10n > 5); // true
console.log(10n === 10); // false (型別不同)
console.log(10n == 10); // true (寬鬆相等)

typeof 檢查

BigInt 有自己的型別標籤。

console.log(typeof 10n); // "bigint"

總結

BigInt 填補了 JavaScript 在大整數處理上的空缺。雖然它不能與 Number 直接運算且不支援小數,但在處理超過 16 位數的識別碼 (ID) 或大額貨幣數值時,它是最安全且不可或缺的工具。