萬盛學電腦網

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

JavaScript 千分位格式化演算法實作與進階優化

前言

金額、數字顯示常需千分位分隔符(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 的倍數個數字且不再有數字
  • 結果:在每組 3 位數字**前**插入逗號,不影響小數點後

進階版:支援科學記號、BigInt、自定義分隔符

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 精確)

舊版瀏覽器 Polyfill (IE10-)

if (!window.Intl || !Intl.NumberFormat) {
    // 引入 intl polyfill: https://github.com/andyearnshaw/Intl.js
    // 或使用舊版 commafy 函數作為 fallback
}

Vue/React 通用過濾器/元件

// 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.30000000000000004IEEE 754 浮點數精度金額用「分」為單位存整數,或用 decimal.js / big.js
parseInt("09") = 0 (舊環境)八進制自動推斷永遠 parseInt(str, 10)
toFixed 四捨五入非銀行家演算法JS 為 round half up財務級用 decimal.js 或後端處理
大數字串 Number() 失真超過 2^53-1用 BigInt 或字串運算庫

總結建議

  1. 現代專案**直接使用 Intl.NumberFormat**,標準、國際化、免維護。
  2. 2. 簡單專案、無國際化需求:封裝 commafy 正則版即可。 3. 金融/會計系統:引入 decimal.js 精確運算,格式化再用 Intl。 4. 顯示與儲存分離:資料庫存數值型別,前端只負責格式化顯示。
copyright © 萬盛學電腦網 all rights reserved