JavaScriptで大整数操作!BigInt()関数の使い方解説
投稿日 2025年02月07日 更新日 2025年02月07日
JavaScript の計算処理で、`9007199254740991` より大きな数値を扱おうとすると正確な計算結果が得られないことがあります。この問題を解決するために `BigInt()` 関数を使用する方法を解説します。
BigInt とは
BigInt は JavaScript で任意精度の整数を扱うためのデータ型です。通常の Number 型では表現できない大きな整数値を安全に処理することができます。
BigInt の基本的な使い方
BigInt を使用するには、以下の2つの方法があります:
// BigInt() 関数を使用する方法
const bigNumber1 = BigInt(9007199254740991);
// 数値の末尾に n をつける方法
const bigNumber2 = 9007199254740991n;
BigInt での計算例
BigInt を使用した計算の例を見てみましょう:
const a = BigInt(9007199254740991);
const b = BigInt(2);
// 加算
console.log(a + b); // 9007199254740993n
// 減算
console.log(a - b); // 9007199254740989n
// 乗算
console.log(a * b); // 18014398509481982n
// 除算
console.log(a / b); // 4503599627370495n
注意点
1. BigInt と通常の数値は混在して計算できません
// エラーが発生する例
const result = BigInt(10) + 5; // TypeError
// 正しい例
const result = BigInt(10) + BigInt(5);
2. 小数点以下は扱えません
// エラーが発生する例
const decimal = BigInt(3.14); // TypeError
3. Math オブジェクトのメソッドは使用できません
// エラーが発生する例
Math.sqrt(BigInt(16)); // TypeError
BigInt の変換
他の型との変換方法も押さえておきましょう:
// BigInt から文字列への変換
const bigNum = BigInt(123);
const str = bigNum.toString(); // "123"
// 文字列から BigInt への変換
const fromStr = BigInt("456"); // 456n
// BigInt から Number への変換(値が安全な範囲内の場合)
const num = Number(BigInt(789)); // 789
実践的な使用例
BigInt は以下のようなケースで特に有用です:
- 大きな ID 値の処理
- 暗号化処理
- 精密な計算が必要な金融関連の処理
// データベースの大きな ID 値を扱う例
const userId = BigInt("9007199254740993");
const nextId = userId + BigInt(1);
// 暗号化処理での使用例
const key = BigInt("0x1234567890abcdef");
以上が BigInt の基本的な使い方です。大きな整数を扱う必要がある場合は、BigInt を活用することで正確な計算結果を得ることができます。
関連記事

新着記事
4
5
6
関連記事
4
5
6


60秒で完了