萬盛學電腦網

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

JavaScript 浮點數運算精度誤差解決方案

問題成因

JavaScript 採用 IEEE 754 雙精度浮點數,二進位無法精確表示某些十進位小數(如 0.1、0.2),導致運算誤差:

0.1 + 0.2  // 0.30000000000000004
1038.1 - 1000 // 38.10000000000002
2232 * 0.1    // 223.20000000000002

解決方案:縮放法

依所需小數位數 n,乘以 10^n 轉為整數運算,再除回:

function mulPrecise(a, b, precision = 2) {
    var factor = Math.pow(10, precision);
    return Math.round(a * b * factor) / factor;
}

// 或通用四捨五入
function roundPrecise(num, precision = 2) {
    var factor = Math.pow(10, precision);
    return Math.round(num * factor) / factor;
}

var total = 2232 * 0.1;        // 223.20000000000002
total = roundPrecise(total, 1); // 223.2

toFixed() 陷阱


(1.005).toFixed(2) // "1.00" ❌ 應為 "1.01"(浮點數 1.005 實際略小)
// 解決:先縮放
Math.round(1.005 * 100) / 100 // 1.01 ✅

現代最佳實踐

  • 金融/金額計算: 使用整數分(分為單位)或專用庫 decimal.js、big.js
  • 一般顯示: num.toFixed(2) 配合 Number() 轉回數值
  • ES2020+: 可考慮 Intl.NumberFormat 格式化顯示

完整工具函式

const MathUtil = {
    add: (a, b, p=2) => Math.round((a+b)*Math.pow(10,p))/Math.pow(10,p),
    sub: (a, b, p=2) => Math.round((a-b)*Math.pow(10,p))/Math.pow(10,p),
    mul: (a, b, p=2) => Math.round((a*b)*Math.pow(10,p))/Math.pow(10,p),
    div: (a, b, p=2) => Math.round((a/b)*Math.pow(10,p))/Math.pow(10,p),
    round: (n, p=2) => Math.round(n*Math.pow(10,p))/Math.pow(10,p)
};

console.log(MathUtil.mul(2232, 0.1, 1)); // 223.2
copyright © 萬盛學電腦網 all rights reserved