JavaScriptの丸め処理:floor・ceil・round・truncの違い

整数に切り下げるにはMath.floor()、切り上げるにはMath.ceil()、最も近い整数に丸めるにはMath.round()、小数部分を取り除くにはMath.trunc()を使います。-1.5ではfloorが-2、残りの3つは-1を返します。

4つの整数化メソッドの比較

floorは入力以下の最大の整数、ceilは入力以上の最小の整数を返します。truncはゼロに近づく方向へ小数部分を取り除きます。roundは最も近い整数を選び、距離が同じなら大きい方を選びます。そのためMath.round(-1.5)は-1です。

入力 floor ceil round trunc
1.4 1 2 1 1
1.5 1 2 2 1
1.6 1 2 2 1
-1.4 -2 -1 -1 -1
-1.5 -2 -1 -1 -1
-1.6 -2 -1 -2 -1
-0.5 -1 -0 -0 -0

ECMAScript仕様のMathメソッド

ページ数の計算と負の数の処理

1ページ20件なら、41件を表示するには余った1件にもページが必要です。Math.ceil(41 / 20)は3になります。40件なら2ページ、0件なら0ページです。1ページあたりの件数には正の整数を指定します。符号のある測定値の整数部分だけが必要な場合はtruncを使います。負の数をfloorで処理すると、値は小さい方の整数へ移動します。

console.log(Math.ceil(41 / 20)); // 3
console.log(Math.ceil(40 / 20)); // 2
console.log(Math.ceil(0 / 20));  // 0

console.log(Math.floor(-1.9)); // -2
console.log(Math.trunc(-1.9)); // -1
console.log(Object.is(Math.round(-0.5), -0)); // true

Math.round(-0.5)は負のゼロ-0を返します。String(-0)は'0'なので、符号を区別するにはObject.is(value, -0)を使います。

小数の桁数や千の位をそろえる

小数第1位までにするには10倍して整数に丸め、10で割ります。第2位までは100を使います。最も近い千の倍数に丸めるには、先に1000で割り、丸めてから1000を掛けます。例の出力は順に1.3、1.25、1.26、1235000です。

console.log(Math.round(1.25 * 10) / 10); // 1.3
console.log(Math.floor(1.256 * 100) / 100); // 1.25
console.log(Math.ceil(1.251 * 100) / 100); // 1.26
console.log(Math.round(1234567 / 1000) * 1000); // 1235000

浮動小数点とtoFixedによる表示

Numberは二進浮動小数点なので、1.005のような十進小数を近似値として保持する場合があります。そのためMath.round(1.005 * 100) / 100は1になります。Number.EPSILONを足しても、すべての符号や大きさで誤差が解消するわけではありません。

console.log(Math.round(1.005 * 100) / 100); // 1
console.log((1.2).toFixed(2)); // "1.20"
console.log(typeof (1.2).toFixed(2)); // "string"

toFixed(2)の結果は'1.20'のような小数2桁の文字列です。末尾のゼロを表示するには文字列のまま使います。十進数で厳密に計算する場合は、単位と丸めの規則を決めて、整数の単位や十進演算用の型を使います。

MDNのtoFixed()リファレンス

同じ入力をブラウザーで比較する

完全な例をUTF-8でrounding-methods.htmlに保存し、ブラウザーで開きます。初期値-1.5の結果は-2, -1, -1, -1です。1.5なら1, 2, 2, 1、-0.5ならfloor以外は-0です。入力欄を空にして実行すると案内が表示されます。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport"
        content="width=device-width, initial-scale=1">
  <title>整数への丸め方を比較</title>
</head>
<body>
  <label for="number">比較する数値</label>
  <input id="number" type="number" step="any" value="-1.5">
  <button id="compare" type="button">結果を比較する</button>
  <pre id="output" aria-live="polite"></pre>
  <script>
    const input = document.querySelector('#number');
    const output = document.querySelector('#output');

    function describe(value) {
      return Object.is(value, -0) ? '-0' : String(value);
    }

    function compare() {
      const raw = input.value.trim();
      const value = raw ? Number(raw) : NaN;
      if (!Number.isFinite(value)) {
        output.textContent = "有限の数値を入力してください。";
        return;
      }
      output.textContent = [
        'floor: ' + describe(Math.floor(value)),
        'ceil: ' + describe(Math.ceil(value)),
        'round: ' + describe(Math.round(value)),
        'trunc: ' + describe(Math.trunc(value)),
      ].join('\n');
    }

    document.querySelector('#compare').addEventListener('click', compare);
    compare();
  </script>
</body>
</html>