Math.round 會把數字四捨五入到最接近的整數。以下範例把 2.5 取整到最近的整數:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to round the number 2.5 to its nearest integer.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Math.round(2.5);
}
</script>
</body>
</html>
輸出 3。
Math.round 的定義是「回傳最接近的整數,若剛好在正中間則往上(往正無窮方向)取」:
Math.round(2.5); // 3 Math.round(2.4); // 2 Math.round(-2.5); // -2 ← 不是 -3!它往大的方向靠 Math.round(-2.6); // -3
第一個反直覺點:負數的 .5 會往 0 的方向靠,所以 -2.5 得到 -2。若你要的是「絕對值意義下的四捨五入」(永遠遠離 0),必須自己處理。
第二個反直覺點是浮點誤差:Math.round(1.005 * 100) / 100 得到 1 而不是 1.01,因為 1.005 在二進位浮點中實際略小於 1.005。這類問題在金額計算上尤其致命。
Math.floor(2.9); // 2,無條件捨去
Math.ceil(2.1); // 3,無條件進位
Math.trunc(-2.7); // -2,直接砍掉小數(與 floor 在負數時不同)
parseInt("2.9px"); // 2,順便解析前綴數字
// 保留 n 位小數的可靠寫法
Number(Math.round(1.005 + Number.EPSILON * 100) / 100);
// 或直接交給 Intl
new Intl.NumberFormat('zh-TW', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(1.005);
涉及金錢計算時,最佳實務是以「最小貨幣單位(例如分)」為整數來運算,最後顯示時再除以 100,避開浮點誤差;若必須用十進位小數,請引入 decimal.js 這類專門的十進位運算庫。