萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript toFixed() 固定小數位數完整教學:格式化、四捨五入與常見坑點

基本語法

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>

核心特性與陷阱

1. 回傳字串,非數值

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 轉回數值。

2. 四捨五入規則:銀行家圍入法?

ES2017 規範採用 Round half away from zero(五捨六入,負數同理),非銀行家圍入法。但浮點數精度問題可能導致直覺不符:

(1.005).toFixed(2) // "1.00" 而非 "1.01"!
// 原因:1.005 在二進位無法精確表示,實際約為 1.004999...

修正方案:先放大再縮小,或使用 Math.round(num * 100) / 100。

3. 參數超出範圍拋出 RangeError

(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)。

copyright © 萬盛學電腦網 all rights reserved