萬盛學電腦網

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

JavaScript toFixed() 精度不一致問題的徹底修復方案

問題現象

原生 Number.prototype.toFixed() 在不同瀏覽器對「銀行家捨入」(五捨六入進位規則)處理不一致:


// 經典案例
(0.005).toFixed(2); 
// IE: "0.00" (向零捨入?)
// Firefox/Chrome: "0.01" (標準四捨五入)
// 規範要求:四捨五入,但浮點數 0.005 實際存儲為 0.004999... 導致差異

階段一:基礎重寫(統一四捨五入邏輯)

Number.prototype.toFixed = function(s) {
    // 核心:乘 10^s + 0.5 取整,再除 10^s
    return (parseInt(this * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();
};

缺陷:結果會自動去除末尾 0,如 (0.05).toFixed(2) 返回 "0.1" 而非 "0.05"。

階段二:完整修復版(保留指定小數位、補齊尾隨 0)

Number.prototype.toFixed = function(s) {
    // 1. 計算四捨五入後的數值
    var changeNum = (parseInt(this * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();

    // 2. 定位小數點
    var index = changeNum.indexOf(".");

    // 3. 無小數點但需要保留小數位 -> 補 .000...
    if (index < 0 && s > 0) {
        changeNum += ".";
        for (var i = 0; i < s; i++) changeNum += "0";
    }
    // 4. 有小數點 -> 計算當前小數位數,補齊到 s 位
    else {
        index = changeNum.length - index - 1; // 當前小數位數
        for (var i = 0; i < (s - index); i++) {
            changeNum += "0";
        }
    }

    return changeNum;
};

測試驗證

console.log((0.005).toFixed(2));   // "0.01" 統一四捨五入
console.log((0.05).toFixed(2));    // "0.05" 保留兩位
console.log((0.5).toFixed(2));     // "0.50" 補齊
console.log((123).toFixed(3));     // "123.000" 整數補齊
console.log((1.005).toFixed(2));   // "1.01" 銀行家捨入修正
console.log((2.675).toFixed(2));   // "2.68" 經典難題修正

進階:通用格式化工具函數(不汙染原型)


/**
 * 精確格式化數字,保留指定小數位,支援負數、科學記數法
 * @param {Number|String} num - 數值
 * @param {Number} decimals - 小數位數 (0-20)
 * @param {Object} options - 選項
 * @returns {String}
 */
function formatNumber(num, decimals = 2, options = {}) {
    const {
        rounding = 'halfUp',   // 'halfUp' | 'halfEven' | 'floor' | 'ceil'
        thousandsSep = '',     // 千分位分隔符
        decimalSep = '.',      // 小數點
        prefix = '',           // 前綴
        suffix = ''            // 後綴
    } = options;

    if (isNaN(num) || !isFinite(num)) return 'NaN';

    // 使用 decimal.js 或 big.js 做精確運算(生產環境推薦)
    // 此處演示純 JS 邏輯
    const neg = num < 0;
    const absNum = Math.abs(Number(num));

    // 精確乘冪
    const factor = Math.pow(10, decimals);
    let fixedNum = Math.round(absNum * factor) / factor; // 簡易四捨五入

    // 格式化字符串
    let str = fixedNum.toFixed(decimals); // 原生 toFixed 此處安全(已四捨五入)
    const parts = str.split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSep);
    str = parts.join(decimalSep);

    return prefix + (neg ? '-' : '') + str + suffix;
}

// 使用
formatNumber(1234.5, 2, { thousandsSep: ',', prefix: '¥' }); // "¥1,234.50"
formatNumber(0.005, 2); // "0.01"

生產環境強烈建議:引入成熟庫

庫優勢toFixed 等效 API
decimal.js 任意精度、多種捨入模式、TypeScript new Decimal(0.005).toFixed(2) → "0.01"
big.js 輕量、精度可配、鏈式 API new Big(0.005).toFixed(2)
accounting.js 專為貨幣格式化、含千分位、貨幣符號 accounting.toFixed(0.005, 2)
numeral.js 格式化功能極豐富(百分比、時間、字節等) numeral(0.005).format('0.00')

避坑指南

  1. 不要修改原型:汙染全局 Number.prototype 易導致第三方庫異常,改用工具函數
  2. 浮點數邊界:1.005、2.675 等二進制無法精確表示的數,純 JS 難以完美處理
  3. 金融系統:後端存儲「分」為單位整數,前端僅做展示格式化
  4. 測試用例:務必覆蓋 0.005, 0.05, 1.005, 2.675, -0.005, 1e-10, 1e21 等邊界值

結語

toFixed() 跨瀏覽器不一致源於浮點數存儲誤差與捨入規則差異。徹底解決需「精確運算 + 格式化輸出」分離:運算層用 decimal.js/big.js,展示層用專業格式化庫。切勿在生產代碼中直接重寫 Number.prototype.toFixed。

copyright © 萬盛學電腦網 all rights reserved