金額、數字顯示常需千分位分隔符(1,234.56)。本文提供從基礎正則替換到 Intl.NumberFormat 現代標準的完整演進,涵蓋整數、小數、負數、大數、區域設定等場景。
function commafy(numStr) {
// 1. 去除空白、非數字字元 (保留 . -)
numStr = String(numStr).trim().replace(/[^\d.-]/g, '');
if (!numStr) return '';
// 2. 分離符號、整數部、小數部
const sign = numStr.startsWith('-') ? '-' : '';
const unsigned = sign ? numStr.slice(1) : numStr;
const [intPart, decPart = ''] = unsigned.split('.');
// 3. 整數部加千分位
const formattedInt = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
// 4. 組合
return sign + formattedInt + (decPart ? '.' + decPart : '');
}
// 測試
console.log(commafy("1234567.89")); // 1,234,567.89
console.log(commafy("-12345")); // -12,345
console.log(commafy(" 1000 ")); // 1,000
/\B(?=(\d{3})+(?!\d))/g\B:非單字邊界 (不在數字開頭)(?=(\d{3})+(?!\d)):正向前瞻,後面是 3 的倍數個數字且不再有數字function formatNumber(value, options = {}) {
const {
locale = 'zh-TW', // 區域設定
style = 'decimal', // 'decimal' | 'currency' | 'percent' | 'unit'
currency, // style=currency 時必填 (如 'TWD')
minimumFractionDigits, // 最少小數位
maximumFractionDigits, // 最多小數位
useGrouping = true, // 是否分組
notation = 'standard' // 'standard' | 'scientific' | 'engineering' | 'compact'
} = options;
// 原生 Intl.NumberFormat (IE11+、所有現代瀏覽器)
const nf = new Intl.NumberFormat(locale, {
style, currency, minimumFractionDigits, maximumFractionDigits,
useGrouping, notation
});
// 處理 BigInt / 大數字串
if (typeof value === 'bigint') return nf.format(value);
if (typeof value === 'string' && value.length > 15) {
// 超過安全整數範圍,嘗試 BigInt
try { return nf.format(BigInt(value.replace(/,/g, ''))); } catch {}
}
return nf.format(Number(value));
}
// 使用範例
console.log(formatNumber(1234567.89)); // 1,234,567.89
console.log(formatNumber(1234567.89, {style:'currency', currency:'TWD'})); // NT$1,234,568
console.log(formatNumber(1234567.89, {notation:'compact'})); // 123 萬
console.log(formatNumber('9999999999999999999')); // 9,999,999,999,999,999,000 (BigInt 精確)
if (!window.Intl || !Intl.NumberFormat) {
// 引入 intl polyfill: https://github.com/andyearnshaw/Intl.js
// 或使用舊版 commafy 函數作為 fallback
}
// Vue 3 全域過濾器 (建議用 composable)
app.config.globalProperties.$filters = {
number(val, opts) { return formatNumber(val, opts); }
};
// 模板:{{ 1234567 | number({style:'currency', currency:'TWD'}) }}
// React 自訂 Hook
function useNumberFormat(locale = 'zh-TW') {
return (val, opts) => formatNumber(val, { ...opts, locale });
}
| 坑點 | 原因 | 解決 |
|---|---|---|
| 0.1 + 0.2 = 0.30000000000000004 | IEEE 754 浮點數精度 | 金額用「分」為單位存整數,或用 decimal.js / big.js |
| parseInt("09") = 0 (舊環境) | 八進制自動推斷 | 永遠 parseInt(str, 10) |
| toFixed 四捨五入非銀行家演算法 | JS 為 round half up | 財務級用 decimal.js 或後端處理 |
| 大數字串 Number() 失真 | 超過 2^53-1 | 用 BigInt 或字串運算庫 |
Intl.NumberFormat**,標準、國際化、免維護。commafy 正則版即可。
3. 金融/會計系統:引入 decimal.js 精確運算,格式化再用 Intl。
4. 顯示與儲存分離:資料庫存數值型別,前端只負責格式化顯示。