處理金額、比率、測量數值時,頻繁需「保留兩位小數」。JS 原生 Number.prototype.toFixed(2) 最常用,但存在四捨五入規則(銀行家捨入)、回傳字串、科學計數法失效等坑點。本文整理 6 種方案與選型指南。
| 方法 | 代碼 | 22.127 → | 22.123 → | 3.1 → | 類型 | 備註 |
|---|---|---|---|---|---|---|
| toFixed(2) | num.toFixed(2) | "22.13" | "22.12" | "3.10" | String | 銀行家捨入,IE≤8 有 Bug |
| Math.round | Math.round(num*100)/100 | 22.13 | 22.12 | 3.1 | Number | 不補零,浮點誤差風險 |
| 正則截斷 | num.toString().match(/^\d+\.\d{2}/)[0] | "22.12" | "22.12" | "3.1" | String | 直接截斷,不四捨五入 |
| Intl.NumberFormat | new Intl.NumberFormat('zh-TW',{minimumFractionDigits:2,maximumFractionDigits:2}).format(num) | "22.13" | "22.12" | "3.10" | String | 地區化、正確四捨五入、效能稍低 |
| 自定義函式(四捨五入+補零) | 見下方 | "22.13" | "22.12" | "3.10" | String | 完全可控,推薦金額場景 |
| 自定義函式(截斷+補零) | 見下方 | "22.12" | "22.12" | "3.10" | String | 財務截斷常用 |
/**
* 格式化為固定兩位小數字串
* @param {number|string} val - 數值
* @param {boolean} round - true=四捨五入(預設), false=截斷
* @returns {string} 如 "3.10", "22.13"
*/
function format2dec(val, round = true) {
const n = Number(val);
if (isNaN(n)) return 'NaN';
const factor = 100;
const adjusted = round ? Math.round(n * factor) : Math.trunc(n * factor);
const [intPart, decPart = ''] = (adjusted / factor).toString().split('.');
return `${intPart}.${(decPart + '00').slice(0, 2)}`;
}
// 測試
console.log(format2dec(22.127456)); // "22.13"
console.log(format2dec(22.123456)); // "22.12"
console.log(format2dec(3.1)); // "3.10"
console.log(format2dec(3.1, false)); // "3.10" (截斷同樣補零)
console.log(format2dec('abc')); // "NaN"
2.675.toFixed(2) === "2.67"(非 2.68),因二進位無法精確表示。金融計算請用 整數分單位 或 decimal.js 庫。(1e-6).toFixed(2) === "0.00" 正常;但極大數可能失精度。Math.trunc(-1.999) === -1(向零截斷),非向下取整。number,僅顯示層格式化為字串。選對工具:一般顯示用 toFixed / Intl.NumberFormat;金融精確計算用整數分或 decimal.js;特殊截斷邏輯用自定義函式。