組み込み関数

JavaScriptのMath入門|数値計算の組み込み関数を使いこなす

Mathは、JavaScriptの数学的な定数と関数を提供する組み込みオブジェクトです。四捨五入、最大値・最小値、乱数生成など、数値計算に必要な機能が揃っています。newを使わずに直接メソッドを呼び出せます。

基本的な使い方

Mathはインスタンスを作成せず、静的メソッドとして使います。丸め処理、絶対値、べき乗などの基本関数を紹介します。

JavaScript
// 丸め処理
console.log(Math.round(4.5));   // 四捨五入
console.log(Math.round(4.4));
console.log(Math.ceil(4.1));    // 切り上げ
console.log(Math.floor(4.9));   // 切り捨て
console.log(Math.trunc(4.9));   // 整数部分のみ
console.log(Math.trunc(-4.9));

// 絶対値
console.log(Math.abs(-42));
console.log(Math.abs(42));

// べき乗と平方根
console.log(Math.pow(2, 10));   // 2の10乗
console.log(2 ** 10);           // 同じ結果(ES2016)
console.log(Math.sqrt(144));    // 平方根
実行結果
5
4
5
4
4
-4
42
42
1024
1024
12

最大値・最小値・乱数

データの範囲チェックや、ランダムな値の生成に使うメソッドです。

JavaScript
// 最大値・最小値
console.log(Math.max(10, 25, 5, 30, 15));
console.log(Math.min(10, 25, 5, 30, 15));

// 配列から最大値・最小値
const scores = [85, 92, 78, 95, 63];
console.log(Math.max(...scores));
console.log(Math.min(...scores));

// 値を範囲内にクランプ
function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
console.log(clamp(150, 0, 100));  // 100に制限
console.log(clamp(-10, 0, 100));  // 0に制限
console.log(clamp(50, 0, 100));   // そのまま

// 乱数(0以上1未満)
console.log(Math.random());

// 指定範囲の整数乱数
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6));   // 1〜6のサイコロ
console.log(randomInt(1, 100)); // 1〜100
実行結果
30
5
95
63
100
0
50
0.7234... (ランダム)
4 (1〜6のランダム)
73 (1〜100のランダム)

実践的な活用例

Mathは価格計算、パーセンテージ、座標計算など実務で多用されます。

JavaScript
// 税込価格の計算(小数点以下切り捨て)
function calcTax(price, taxRate = 0.1) {
  return Math.floor(price * (1 + taxRate));
}
console.log("税込:", calcTax(1980), "円");

// パーセンテージ(小数第1位まで)
function percentage(part, total) {
  return Math.round((part / total) * 1000) / 10;
}
console.log("達成率:", percentage(73, 100), "%");

// 2点間の距離
function distance(x1, y1, x2, y2) {
  return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
console.log("距離:", Math.round(distance(0, 0, 3, 4)));

// 配列からランダムに要素を選択
function pickRandom(array) {
  return array[Math.floor(Math.random() * array.length)];
}
const colors = ["赤", "青", "緑", "黄", "紫"];
console.log("ランダム選択:", pickRandom(colors));

// 配列をシャッフル(Fisher-Yates)
function shuffle(array) {
  const arr = [...array];
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}
console.log("シャッフル:", shuffle([1, 2, 3, 4, 5]));
実行結果
税込: 2178 円
達成率: 73 %
距離: 5
ランダム選択: 青
シャッフル: [3, 5, 1, 4, 2]
主要なMath定数

Math.PI(円周率 3.14159...)、Math.E(自然対数の底 2.71828...)、Math.LN2(2の自然対数)、Math.SQRT2(2の平方根)などが定義されています。

浮動小数点の精度に注意

JavaScriptは浮動小数点演算のため、0.1 + 0.2 !== 0.3になります。金額計算では整数(円単位)で計算するか、Math.round()で丸め処理を行ってください。Math.random()は暗号学的に安全ではないため、セキュリティ用途にはcrypto.getRandomValues()を使用してください。

まとめ

  • Mathはインスタンス不要で静的メソッドとして使う
  • round()/ceil()/floor()/trunc()で丸め処理
  • max()/min()は配列にはスプレッド演算子と組み合わせる
  • Math.random()で0以上1未満の乱数を生成
  • 金額計算では浮動小数点の精度に注意する