萬盛學電腦網

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

JavaScript 浮點數運算精度誤差根因與四大修正方案

經典現場

console.log(0.1 + 0.2 === 0.3); // false
console.log(0.1 + 0.2);         // 0.30000000000000004
console.log(1.4 - 1.3);         // 0.10000000000000003
console.log(0.7 * 1.8);         // 1.2599999999999999

根因:IEEE 754 雙精度浮點數表示

  • JS 只有一種數字型別:Number (64 位雙精度浮點數)。
  • 十進位小數多無法用二進位有限位精確表示 (如 0.1 = 0.0001100110011... 循環)。
  • 儲存時截斷捨入,運算時誤差累積。

方案一:整數放大法 (最通用、效能最好)

/**
 * 精確四則運算:放大為整數運算,再縮小
 * @param {number} a
 * @param {number} b
 * @param {string} op - 'add' | 'sub' | 'mul' | 'div'
 * @param {number} [precision] - 保留小數位 (預設自動推斷)
 */
function preciseCalc(a, b, op, precision) {
    // 1. 取得小數位數
    function getDecimals(n) {
        var s = n.toString();
        return s.includes('.') ? s.length - s.indexOf('.') - 1 : 0;
    }
    var d1 = getDecimals(a), d2 = getDecimals(b);
    var maxD = precision ?? Math.max(d1, d2);
    var m = Math.pow(10, maxD);
    
    // 2. 放大為整數 (Math.round 避免 0.1 * 10 = 1.0000000000000001)
    var intA = Math.round(a * m);
    var intB = Math.round(b * m);
    
    // 3. 整數運算
    var result;
    switch (op) {
        case 'add': result = intA + intB; break;
        case 'sub': result = intA - intB; break;
        case 'mul': result = (intA * intB) / m; break; // 乘法需再除一次 m
        case 'div': result = (intA / intB); break;     // 除法不需再縮放
        default: throw new Error('Unknown op');
    }
    
    // 4. 縮小並修正浮點殘留
    return Number((result / m).toFixed(maxD));
}

// 封裝常用方法
const Precise = {
    add: (a, b, p) => preciseCalc(a, b, 'add', p),
    sub: (a, b, p) => preciseCalc(a, b, 'sub', p),
    mul: (a, b, p) => preciseCalc(a, b, 'mul', p),
    div: (a, b, p) => preciseCalc(a, b, 'div', p),
    round: (n, d) => Number(n.toFixed(d))
};

// 測試
console.log(Precise.add(0.1, 0.2) === 0.3); // true
console.log(Precise.mul(0.7, 1.8));         // 1.26
console.log(Precise.div(1.4, 1.3));         // 1.0769230769230769 (循環小數仍有誤差,需指定精度)
console.log(Precise.div(1.4, 1.3, 2));      // 1.08

方案二:toFixed() + parseFloat() (簡單場景)

function add(a, b) {
    return parseFloat((a + b).toFixed(10)); // 保留 10 位通常足夠
}
console.log(add(0.1, 0.2)); // 0.3

⚠️ 缺點:toFixed 四捨五入規則在邊界值 (如 1.005) 可能因浮點誤差導致錯誤方向。

方案三:專業庫 decimal.js / big.js / math.js (金融/科學計算必備)

// decimal.js 範例
import Decimal from 'decimal.js';

var a = new Decimal('0.1');
var b = new Decimal('0.2');
console.log(a.plus(b).equals(0.3)); // true
console.log(a.times(1.8).toFixed(2)); // '1.26'

// 支援任意精度、科學記號、模數、開根號、三角函數...
庫體積 (gz)特色
big.js~2.5KB極簡、僅支援基本四則運算、定點數
decimal.js~12KB功能完整、任意精度、數學函數豐富
math.js~50KB龐大數學庫、矩陣、單位、解析器

方案四:Intl.NumberFormat 只做顯示格式化 (不修正運算)

var num = 0.1 + 0.2; // 0.30000000000000004
console.log(new Intl.NumberFormat('zh-TW', { maximumFractionDigits: 2 }).format(num)); // "0.30"
// 僅供顯示,底層數值未變

避坑清單

  • 貨幣計算:後端用整數分 (分/錢) 存儲,前端只做顯示轉換,或全程用 decimal.js。
  • 比較浮點數:Math.abs(a - b) < Number.EPSILON (ES2015) 或自訂 epsilon = 1e-10。
  • JSON 傳輸:後端序列化為字串 "123.45",前端 new Decimal(str) 還原,避免精度損失。
  • 避免連續運算累積誤差:單筆運算即修正,或用整數分單位贯穿始終。
copyright © 萬盛學電腦網 all rights reserved