number.toFixed(digits)
digits:0 ~ 20 之間的整數,指定小數點後位數<script>
var num = 4.2343;
console.log(num.toFixed(0)); // "4"
console.log(num.toFixed(1)); // "4.2"
console.log(num.toFixed(2)); // "4.23"
console.log(num.toFixed(3)); // "4.234"
console.log(num.toFixed(4)); // "4.2343"
console.log(num.toFixed(5)); // "4.23430" 自動補零
// 負數行為
console.log((-4.2343).toFixed(2)); // "-4.23"
// 科學記號大數
console.log((1.23e+20).toFixed(2)); // "123000000000000000000.00"
</script>
var a = 1.5;
var b = a.toFixed(1); // "1.5" (String)
console.log(typeof b); // "string"
console.log(b + 1); // "1.51" 字串串接,非數學加法!
解決:Number(b) 或 +b 轉回數值。
ES2017 規範採用 Round half away from zero(五捨六入,負數同理),非銀行家圍入法。但浮點數精度問題可能導致直覺不符:
(1.005).toFixed(2) // "1.00" 而非 "1.01"!
// 原因:1.005 在二進位無法精確表示,實際約為 1.004999...
修正方案:先放大再縮小,或使用 Math.round(num * 100) / 100。
(1.23).toFixed(-1) // RangeError
(1.23).toFixed(21) // RangeError
(1.23).toFixed(3.14) // 3.14 被 ToInteger 轉為 3
function roundFixed(num, digits) {
var factor = Math.pow(10, digits);
// 使用 toPrecision 輔助或 epsilon 修正
return (Math.round(num * factor + Number.EPSILON) / factor).toFixed(digits);
}
console.log(roundFixed(1.005, 2)); // "1.01" 正確
price.toFixed(2) 確保兩位小數(ratio * 100).toFixed(1) + '%'toFixed() 是格式化顯示的利器,但必須牢記:回傳字串、四捨五入受浮點誤差影響、參數需在 0~20。涉及金融計算時,建議搭配整數分單位運算或專用庫(如 decimal.js)。