数値計算

Math toFixed parseInt Intl.NumberFormat

数値の演算・変換・フォーマット処理をまとめます。浮動小数点の注意点も重要です。

デモ:数値変換をリアルタイム確認

toFixed(2)3.14
Math.round3
Math.floor3
Math.ceil4
Math.abs3.14159
Intl.NumberFormat(日本語)3.142
Intl(通貨)¥3
toString(2)(2進数)11
toString(16)(16進数)3

コード例:数値処理

js
// 文字列 → 数値の変換
parseInt("42");           // 42(整数)
parseInt("0xFF", 16);     // 255(16進数→10進数)
parseFloat("3.14");       // 3.14(浮動小数点)
Number("42");             // 42(厳密な変換)
+"42";                    // 42(+ 演算子)

// 数値チェック
Number.isNaN(NaN);        // true(グローバルisNaNより安全)
Number.isFinite(Infinity); // false
Number.isInteger(3.0);    // true
Number.isSafeInteger(Number.MAX_SAFE_INTEGER); // true

// 丸め処理
Math.round(3.5);   // 4(四捨五入)
Math.floor(3.9);   // 3(切り捨て)
Math.ceil(3.1);    // 4(切り上げ)
Math.trunc(3.9);   // 3(小数部を捨てる)
(3.14159).toFixed(2); // "3.14"(文字列で返る)

// Math ユーティリティ
Math.max(1, 5, 3);    // 5
Math.min(1, 5, 3);    // 1
Math.abs(-5);         // 5(絶対値)
Math.pow(2, 10);      // 1024(べき乗)
2 ** 10;              // 1024(** 演算子でも同じ)
Math.sqrt(16);        // 4(平方根)
Math.random();        // 0〜1の乱数

// ランダムな整数(min〜max)
Math.floor(Math.random() * (max - min + 1)) + min;

⚠️ 浮動小数点の罠

JavaScriptはIEEE 754倍精度浮動小数点数を使うため、小数計算に誤差が生じます。

js
// 有名な落とし穴
0.1 + 0.2;           // 0.30000000000000004 ❌

// 対策①:toFixed で丸める
(0.1 + 0.2).toFixed(1);  // "0.3"(文字列)
Number((0.1 + 0.2).toFixed(1)); // 0.3

// 対策②:整数に変換して計算
(0.1 * 10 + 0.2 * 10) / 10; // 0.3 ✅

// 対策③:誤差を考慮した比較
Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON; // true

// 金額計算は整数(銭単位)で扱う
// 例:¥1.50 → 150(銭)として計算

NEWBigInt(巨大整数)と Intl.NumberFormat の拡張

js
// BigInt:Number.MAX_SAFE_INTEGER を超える整数
const big = 9007199254740993n;  // n サフィックス
BigInt(9007199254740993);        // 変換
big + 1n;                        // 9007199254740994n
// Number との混在は不可(TypeError)

// Intl.NumberFormat の拡張(モダン)
new Intl.NumberFormat('ja-JP', {
  notation: 'compact',    // 1万、10億などの略記
}).format(1234567);        // "123万"

new Intl.NumberFormat('ja-JP', {
  signDisplay: 'always',  // 正数にも + を表示
}).format(42);             // "+42"

// 単位付きフォーマット
new Intl.NumberFormat('ja-JP', {
  style: 'unit',
  unit: 'kilometer',
}).format(42);             // "42 km" 

🤖 AIプロンプトテンプレート

以下のようなJavaScriptの数値演算に関するサンプルコードを生成してください:
- Math.floor / Math.ceil / Math.round / Math.truncによる丸め処理
- Math.random()を使った指定範囲の乱数生成
- 浮動小数点誤差(0.1+0.2問題)とNumber.EPSILONを使った対策
- parseInt / parseFloat / Numberによる文字列から数値への変換
- Intl.NumberFormatを使った通貨・コンパクト表記などのフォーマット

⚠️ このプロンプトはあくまでたたき台です。AIの回答はモデルやバージョン、会話の文脈によって毎回異なります。意図通りに動かない場合は、条件を追記・修正してお使いください。