JavaScript の数値計算は算術演算子と Math オブジェクトの組み合わせが基本です。四捨五入、乱数生成、べき乗など、Math には実務で頻出するメソッドが多数用意されています。一方で 0.1 + 0.2 !== 0.3 になる浮動小数点の誤差は JavaScript 特有のハマりポイントです。この記事では Math オブジェクトの主要メソッドを網羅し、浮動小数点の対策まで解説します。
この記事でわかること
・算術演算子(+, -, *, /, %, **)の基本
・Math.round / Math.floor / Math.ceil で四捨五入・切り捨て・切り上げ
・Math.random で乱数を生成する方法
・Math.abs / Math.max / Math.min / Math.sqrt / Math.pow
・Math.PI / Math.E / Math.LOG2E などの定数
・浮動小数点の誤差(0.1 + 0.2 問題)と対策
・toFixed の注意点
・金額計算・税込計算・ランダム抽選の実務パターン
・算術演算子(+, -, *, /, %, **)の基本
・Math.round / Math.floor / Math.ceil で四捨五入・切り捨て・切り上げ
・Math.random で乱数を生成する方法
・Math.abs / Math.max / Math.min / Math.sqrt / Math.pow
・Math.PI / Math.E / Math.LOG2E などの定数
・浮動小数点の誤差(0.1 + 0.2 問題)と対策
・toFixed の注意点
・金額計算・税込計算・ランダム抽選の実務パターン
算術演算子の一覧
| 演算子 | 意味 | 例 | 結果 |
|---|---|---|---|
+ |
加算 | 10 + 3 |
13 |
- |
減算 | 10 - 3 |
7 |
* |
乗算 | 10 * 3 |
30 |
/ |
除算 | 10 / 3 |
3.333… |
% |
剰余(余り) | 10 % 3 |
1 |
** |
べき乗 | 2 ** 10 |
1024 |
JavaScript
console.log(10 + 3); // 13 console.log(10 - 3); // 7 console.log(10 * 3); // 30 console.log(10 / 3); // 3.3333333333333335 console.log(10 % 3); // 1(余り) console.log(2 ** 10); // 1024(2の10乗)
剰余(%)の活用
JavaScript
// 偶数・奇数の判定
console.log(4 % 2 === 0); // true(偶数)
console.log(5 % 2 === 0); // false(奇数)
// 配列のインデックスを循環させる
const colors = ["red", "green", "blue"];
for (let i = 0; i < 6; i++) {
console.log(colors[i % colors.length]);
// red, green, blue, red, green, blue
}
四捨五入・切り捨て・切り上げ
| メソッド | 動作 | 7.5 | 7.4 | -7.5 |
|---|---|---|---|---|
Math.round() |
四捨五入 | 8 | 7 | -7 |
Math.floor() |
切り捨て(小さい方向) | 7 | 7 | -8 |
Math.ceil() |
切り上げ(大きい方向) | 8 | 8 | -7 |
Math.trunc() |
小数部を除去(0方向に切り捨て) | 7 | 7 | -7 |
JavaScript
console.log(Math.round(7.5)); // 8 console.log(Math.round(7.4)); // 7 console.log(Math.floor(7.9)); // 7 console.log(Math.ceil(7.1)); // 8 console.log(Math.trunc(7.9)); // 7 console.log(Math.trunc(-7.9)); // -7(floorと違い0方向)
小数点 N 桁で四捨五入する
JavaScript
// 小数点第2位で四捨五入
function roundTo(num, decimals) {
const factor = 10 ** decimals;
return Math.round(num * factor) / factor;
}
console.log(roundTo(3.14159, 2)); // 3.14
console.log(roundTo(1.005, 2)); // 1(※浮動小数点の誤差で1.00になる)
Math.round(1.005 * 100) / 100 は 1.00 になります(1.005 * 100 が 100.49999… になるため)。後述の浮動小数点対策を参照してください。Math.random で乱数を生成する
Math.random() は 0 以上 1 未満の浮動小数点数を返します。これを加工して任意の範囲の整数や小数を生成します。
JavaScript
// 0以上1未満の小数
console.log(Math.random()); // 0.7293847...
// 0〜9 の整数
console.log(Math.floor(Math.random() * 10));
// 1〜10 の整数
console.log(Math.floor(Math.random() * 10) + 1);
// min〜max の整数(汎用関数)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 100)); // 1〜100のランダムな整数
Math.random() は暗号学的に安全ではありません。パスワード生成やトークン生成には crypto.getRandomValues() を使ってください。Math オブジェクトの主要メソッド・定数
| メソッド / 定数 | 説明 | 例 | 結果 |
|---|---|---|---|
Math.abs(x) |
絶対値 | Math.abs(-5) |
5 |
Math.max(a, b, ...) |
最大値 | Math.max(1, 5, 3) |
5 |
Math.min(a, b, ...) |
最小値 | Math.min(1, 5, 3) |
1 |
Math.sqrt(x) |
平方根 | Math.sqrt(9) |
3 |
Math.pow(x, y) |
x の y 乗 | Math.pow(2, 3) |
8 |
Math.sign(x) |
符号(-1 / 0 / 1) | Math.sign(-5) |
-1 |
Math.log(x) |
自然対数 | Math.log(Math.E) |
1 |
Math.PI |
円周率 π | — | 3.14159… |
Math.E |
ネイピア数 e | — | 2.71828… |
配列から最大値・最小値を取得する
const scores = [85, 92, 78, 96, 88]; // スプレッド構文で配列を展開 console.log(Math.max(...scores)); // 96 console.log(Math.min(...scores)); // 78
Math.max() は引数なしで -Infinity、Math.min() は引数なしで Infinity を返します。配列が空の場合の処理に注意してください。浮動小数点の誤差(0.1 + 0.2 問題)
JavaScript の数値は IEEE 754 の倍精度浮動小数点数で表現されるため、一部の小数を正確に表現できません。
JavaScript
console.log(0.1 + 0.2); // 0.30000000000000004 console.log(0.1 + 0.2 === 0.3); // false console.log(0.3 - 0.1); // 0.19999999999999998 console.log(1.005 * 100); // 100.49999999999999
対策: 整数に変換して計算する
JavaScript
// 金額計算: 円単位(整数)で計算し、最後に変換 const price = 1000; // 円 const taxRate = 0.1; // NG: 浮動小数点の誤差が出る可能性 // const total = price * (1 + taxRate); // OK: 整数で計算 const total = Math.round(price * (1 + taxRate)); console.log(total); // 1100
対策: Number.EPSILON で比較する
JavaScript
function isEqual(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
console.log(isEqual(0.1 + 0.2, 0.3)); // true
toFixed の注意点
JavaScript
// toFixed は文字列を返す console.log((0.1 + 0.2).toFixed(1)); // "0.3"(文字列) console.log(typeof (0.1 + 0.2).toFixed(1)); // "string" // 数値に戻す場合 console.log(Number((0.1 + 0.2).toFixed(1))); // 0.3 // 銀行丸め問題: 1.005 が正しく四捨五入されない console.log((1.005).toFixed(2)); // "1.00"(期待値は "1.01")
toFixed は文字列を返すため、計算に使う場合は Number() や parseFloat() で数値に変換してください。また、1.005 が “1.00” になる銀行丸め問題にも注意が必要です。実務でよく使うパターン
税込金額の計算
JavaScript
function calcTaxIncluded(price, taxRate = 0.10) {
return Math.round(price * (1 + taxRate));
}
console.log(calcTaxIncluded(980)); // 1078
console.log(calcTaxIncluded(1500)); // 1650
配列からランダムに 1 つ選ぶ
JavaScript
function pickRandom(array) {
return array[Math.floor(Math.random() * array.length)];
}
const prizes = ["1等", "2等", "3等", "残念"];
console.log(pickRandom(prizes)); // ランダムに1つ選ばれる
数値を指定範囲内に制限する(clamp)
JavaScript
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
console.log(clamp(150, 0, 100)); // 100(上限に制限)
console.log(clamp(-5, 0, 100)); // 0(下限に制限)
console.log(clamp(50, 0, 100)); // 50(範囲内はそのまま)
割合(パーセンテージ)の計算
JavaScript
function percentage(part, total, decimals = 1) {
if (total === 0) return 0;
const pct = (part / total) * 100;
return Number(pct.toFixed(decimals));
}
console.log(percentage(3, 7)); // 42.9
console.log(percentage(15, 20)); // 75.0
関連記事
- 四則演算と計算の基本 — 算術演算子・Math・小数計算
- 四捨五入を行う方法
- 乱数を生成する方法
- 演算子の使い方と例まとめ
- 指定した桁数のランダムな文字列を生成する方法
- input に入力された数値の計算結果をリアルタイム表示する方法
よくある質問
Q0.1 + 0.2 が 0.3 にならないのはなぜですか?
AJavaScript の数値は IEEE 754 倍精度浮動小数点数で、0.1 や 0.2 を正確に表現できないためです。
0.1 + 0.2 は 0.30000000000000004 になります。対策として、整数に変換して計算するか、Number.EPSILON を使った比較を行います。QMath.round と toFixed の違いは何ですか?
A
Math.round() は数値を返し、toFixed() は文字列を返します。toFixed は小数桁数を指定できますが、結果が文字列のため計算に使う場合は Number() で変換が必要です。また toFixed には 1.005 → “1.00” になる誤差問題があります。QMath.floor と Math.trunc の違いは?
A正の数では同じ結果ですが、負の数で異なります。
Math.floor(-7.1) は -8(小さい方向)、Math.trunc(-7.1) は -7(0 方向)です。QMath.random() は暗号学的に安全ですか?
Aいいえ。
Math.random() は擬似乱数であり、予測可能です。パスワードやトークンの生成には crypto.getRandomValues()(ブラウザ)または crypto.randomBytes()(Node.js)を使ってください。Q配列の最大値を Math.max で取得するにはどうすればよいですか?
A
Math.max(...array) でスプレッド構文を使って配列を展開します。ただし、配列が非常に大きい(数万件以上)場合はスタックオーバーフローの可能性があるため、array.reduce((a, b) => Math.max(a, b)) を使ってください。まとめ
JavaScript の計算と Math オブジェクトの使い方を整理しました。
- 算術演算子:
+ - * / %に加えて**(べき乗) - 丸め処理: round(四捨五入)/ floor(切り捨て)/ ceil(切り上げ)/ trunc(小数除去)
- 乱数:
Math.floor(Math.random() * (max - min + 1)) + min - 浮動小数点: 0.1 + 0.2 問題 → 整数変換か Number.EPSILON で対策
- toFixed: 文字列を返す点と銀行丸め問題に注意
金額計算では整数(円単位)で処理し最後に Math.round で丸める、乱数はセキュリティ用途には crypto を使うなど、実務での注意点を押さえておきましょう。