← 中文资源

简体中文版本

floor trunc 与 ceil 在负数上分道扬镳

floor/trunc/ceil 在正数上一致、负数上方向不同,Math.round 的 .5 恒向正无穷取整:分桶与索引必须显式选对方向,否则负值会掉进错误的桶。

阅读英文原文

运行结果

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

2.7 | floor 2 | trunc 2 | ceil 3
-2.7 | floor -3 | trunc -2 | ceil -2
2.3 | floor 2 | trunc 2 | ceil 3
-2.3 | floor -3 | trunc -2 | ceil -2
round(-2.5) = -2 | round(2.5) = 3
round(-0.5) = -0 | floor(-0.5) = -1
trunc(-2.9) = -2 | trunc(2.9) = 2
floor(-0.2) = -1 | trunc(-0.2) = -0

实现说明

文件的主干是一个循环——for (const v of values)。 values 定义在模块顶层,中间不经过函数作用域。

使用要点

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

常见问题

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件用顶层绑定保存自己的状态:values。

核心语句

const values = [2.7, -2.7, 2.3, -2.3];

代码示例

// The three rounding functions agree on positives and diverge on negatives: floor toward -Infinity, trunc toward 0, ceil toward +Infinity
const values = [2.7, -2.7, 2.3, -2.3];
for (const v of values) {
  console.log(
    v,
    '| floor', Math.floor(v),
    '| trunc', Math.trunc(v),
    '| ceil', Math.ceil(v),
  );
}

// round rounds .5 toward +Infinity: -2.5 becomes -2 not -3, and -0.5 lands on -0
console.log('round(-2.5) =', Math.round(-2.5), '| round(2.5) =', Math.round(2.5));
console.log('round(-0.5) =', Math.round(-0.5), '| floor(-0.5) =', Math.floor(-0.5));

// trunc chops the fraction off, same for both signs - for "drop the decimals" rather than "round down"
console.log('trunc(-2.9) =', Math.trunc(-2.9), '| trunc(2.9) =', Math.trunc(2.9));

// Decide the direction before bucketing/indexing: whether -0.2 lands in bucket 0 or -1 changes membership
console.log('floor(-0.2) =', Math.floor(-0.2), '| trunc(-0.2) =', Math.trunc(-0.2));