实现说明
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));