JavaScript 中 小数转整数怎么舍入
javascript 中小数转整数没有单一的默认行为,而是根据需求选择 math.floor()、math.ceil()、math.round() 或 math.trunc()。若需向下取整使用 math.floor(),向上取整使用 math.ceil(),四舍五入使用 math.round(),而直接截断小数部分则使用 math.trunc()。这些方法均返回 number 类型,且对正负数的处理逻辑存在差异,特别是 math.trunc() 与位运算在负数表现上不同。

Math.floor() 和 Math.ceil() 的边界行为
Math.floor() 始终向负无穷方向取整,Math.ceil() 始终向正无穷方向取整。对于正数,floor 去掉小数,ceil 进位;对于负数,floor 会减小数值(如 -1.1 变为 -2),ceil 会增大数值(如 -1.1 变为 -1)。这种对称性使得它们在处理范围判断时非常可靠。

console.log(Math.floor(3.7)); // 3 console.log(Math.floor(-3.7)); // -4 console.log(Math.ceil(3.2)); // 4 console.log(Math.ceil(-3.2)); // -3
Math.round() 的四舍五入规则
Math.round() 执行标准的四舍五入,将数字舍入到最接近的整数。如果小数部分正好是 0.5,它会向绝对值更大的方向舍入(即远离零的方向)。例如 1.5 变为 2,-1.5 变为 -2。这一特性在处理临界值时需要特别注意,因为它不符合某些业务场景下“遇半进一”或“遇半去尾”的直觉。
立即学习“Java免费学习笔记(深入)”;

console.log(Math.round(1.5)); // 2 console.log(Math.round(1.49)); // 1 console.log(Math.round(-1.5)); // -2 console.log(Math.round(-1.6)); // -2
Math.trunc() 与位运算截断的区别
Math.trunc() 专门用于移除小数部分,只保留整数部分,类似于 C 语言中的强制类型转换。它与 Math.floor() 在正数上一致,但在负数上不同:Math.trunc(-3.7) 结果为 -3,而 Math.floor(-3.7) 结果为 -4。此外,位运算如 ~~x 或 x | 0 也能实现截断,但它们会将结果限制在 32 位有符号整数范围内,超出范围会导致溢出,而 Math.trunc() 支持双精度浮点数范围内的所有整数。


















