← 中文资源

简体中文版本

Math.round 把 .5 一律向上舍

round/trunc/floor/ceil 在负数与 .5 上各不相同:round 把 .5 一律舍向 +Infinity(-0.5 得 -0)、trunc 砍小数、floor 与 ceil 方向相反。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

-2.5 round=-2 trunc=-2 floor=-3 ceil=-2
-1.5 round=-1 trunc=-1 floor=-2 ceil=-1
-0.5 round=0 trunc=0 floor=-1 ceil=0
0.5 round=1 trunc=0 floor=0 ceil=1
1.5 round=2 trunc=1 floor=1 ceil=2
2.5 round=3 trunc=2 floor=2 ceil=3
round(-0.5) is -0: true
trunc symmetric: true
floor vs ceil: -1 -0

实现说明

for (const n of [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]) 承担全部的逐项处理。

使用要点

  • 直接运行文件,输出会带上标签,比如 round(-0.5) is -0:、trunc symmetric:、floor vs ceil:——输出的每一行都能指回产生它的那次调用。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。

代码示例

// 四个舍入函数在负数与 .5 上的行为各不相同
for (const n of [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]) {
  console.log(
    n,
    'round=' + Math.round(n),
    'trunc=' + Math.trunc(n),
    'floor=' + Math.floor(n),
    'ceil=' + Math.ceil(n),
  );
}

// round 对 .5 一律向 +Infinity:-0.5 得 -0,不是 -1
console.log('round(-0.5) is -0:', Object.is(Math.round(-0.5), -0));

// trunc 直接砍掉小数部分,正负对称
console.log('trunc symmetric:', Math.trunc(-4.7) === -4 && Math.trunc(4.7) === 4);

// floor 向 -Infinity、ceil 向 +Infinity,方向相反
console.log('floor vs ceil:', Math.floor(-0.1), Math.ceil(-0.1));