Math.round(x) // 返回最接近的整數,.5 向正無窮方向捨入
x ≥ 0:0.5 → 1,0.49 → 0(標準四捨五入)。x < 0:-0.5 → 0,-0.51 → -1,**向零方向較大值捨入**(非絕對值四捨五入)。console.log(Math.round(0.5)); // 1
console.log(Math.round(20.7)); // 21
console.log(Math.round(20.3)); // 20
console.log(Math.round(-20.3)); // -20
console.log(Math.round(-20.5)); // -20 (關鍵:-20.5 → -20,非 -21)
console.log(Math.round(-20.51)); // -21
| x | round | floor(向下) | ceil(向上) | trunc(截斷) |
|---|---|---|---|---|
| 2.9 | 3 | 2 | 3 | 2 |
| 2.1 | 2 | 2 | 3 | 2 |
| -2.1 | -2 | -3 | -2 | -2 |
| -2.9 | -3 | -3 | -2 | -2 |
| -2.5 | -2 | -3 | -2 | -2 |
function roundTo(num, decimals) {
const factor = Math.pow(10, decimals);
return Math.round(num * factor) / factor;
}
console.log(roundTo(1.2345, 2)); // 1.23
console.log(roundTo(1.235, 2)); // 1.24 (注意浮點誤差可能導致 1.23)
// 更穩健:Number(num.toFixed(decimals)) 或使用 decimal.js
Math.round 是**商業捨入**(.5 向正無窮)。財務常需**銀行家捨入**(.5 向最近偶數):
function bankersRound(num, decimals = 0) {
const factor = Math.pow(10, decimals);
const scaled = num * factor;
const floored = Math.floor(scaled);
const diff = scaled - floored;
if (diff === 0.5) return (floored % 2 === 0 ? floored : floored + 1) / factor;
return Math.round(scaled) / factor;
}
console.log(bankersRound(1.5)); // 2
console.log(bankersRound(2.5)); // 2 (向偶數)
console.log(bankersRound(3.5)); // 4