JavaScript 取整:floor、ceil、round 和 trunc 的区别

向下取整用 Math.floor(),向上取整用 Math.ceil(),取最接近的整数用 Math.round(),去掉小数部分用 Math.trunc()。输入 -1.5 时,floor 返回 -2,其余三个方法返回 -1。

比较四种取整方式

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 方法规范

计算页数与处理负数

每页 20 条时,41 条记录需要 3 页,因为多出的 1 条也要占一页。使用 Math.ceil(41 / 20)。40 条需要 2 页,0 条则计算出 0 页。每页条数必须是正整数。带符号的测量值只需要整数部分时,用 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) 检查。

按小数位或千位取整

保留一位小数时,先乘以 10,执行取整,再除以 10。保留两位时使用 100。若要舍入到最接近的 1000 的倍数,先除以 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 显示格式

JavaScript 的 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'。需要末尾的零时,请保留字符串。需要精确的十进制运算时,应先确定单位和舍入规则,再使用整数单位或支持十进制运算的类型。

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="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport"
        content="width=device-width, initial-scale=1">
  <title>比较 JavaScript 取整方式</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>