萬盛學電腦網

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

JavaScript 浮點數精確加法:accAdd 算法原理與現代替代方案

問題根源


0.1 + 0.2; // 0.30000000000000004 ❌
12.11 + 12.22; // 24.330000000000002 ❌

原因:IEEE 754 雙精度浮點數無法精確表示十進制小數,二進制表示存在無限循環。

經典解決方案:accAdd 縮放算法


/**
 * 精確加法
 * @param {number|string} arg1
 * @param {number|string} arg2
 * @returns {number} 精確相加結果
 */
function accAdd(arg1, arg2) {
  // 轉字符串獲取小數位數
  const s1 = arg1.toString();
  const s2 = arg2.toString();
  
  // 計算小數位數
  const r1 = s1.includes('.') ? s1.split('.')[1].length : 0;
  const r2 = s2.includes('.') ? s2.split('.')[1].length : 0;
  
  // 取最大小數位,計算縮放因子
  const m = Math.pow(10, Math.max(r1, r2));
  
  // 縮放為整數相加,再縮放回來
  return (arg1 * m + arg2 * m) / m;
}

// 測試
console.log(accAdd(0.1, 0.2));       // 0.3 ✅
console.log(accAdd(12.11, 12.22));   // 24.33 ✅
console.log(accAdd('12.11', '12.22')); // 24.33 ✅ 支持字符串輸入

完整精確運算庫:加減乘除


const PreciseMath = {
  // 加法
  add(arg1, arg2) {
    const s1 = arg1.toString(), s2 = arg2.toString();
    const m = Math.pow(10, Math.max(
      s1.includes('.') ? s1.split('.')[1].length : 0,
      s2.includes('.') ? s2.split('.')[1].length : 0
    ));
    return (arg1 * m + arg2 * m) / m;
  },
  
  // 減法:a - b = a + (-b)
  sub(arg1, arg2) {
    return this.add(arg1, -arg2);
  },
  
  // 乘法
  mul(arg1, arg2) {
    const s1 = arg1.toString(), s2 = arg2.toString();
    const m = (s1.includes('.') ? s1.split('.')[1].length : 0) +
              (s2.includes('.') ? s2.split('.')[1].length : 0);
    return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
  },
  
  // 除法
  div(arg1, arg2) {
    const s1 = arg1.toString(), s2 = arg2.toString();
    const t1 = s1.includes('.') ? s1.split('.')[1].length : 0;
    const t2 = s2.includes('.') ? s2.split('.')[1].length : 0;
    const r1 = Number(s1.replace('.', ''));
    const r2 = Number(s2.replace('.', ''));
    return (r1 / r2) * Math.pow(10, t2 - t1);
  }
};

// 使用
console.log(PreciseMath.add(0.1, 0.2));    // 0.3
console.log(PreciseMath.sub(1.0, 0.9));    // 0.1
console.log(PreciseMath.mul(0.1, 0.2));    // 0.02
console.log(PreciseMath.div(0.3, 0.1));    // 3

現代最佳替代方案

1. decimal.js / big.js (生產環境首選)


// npm install decimal.js
import Decimal from 'decimal.js';

const result = new Decimal('0.1').plus('0.2'); // Decimal { "0.3" }
result.toNumber(); // 0.3
result.toFixed(2); // "0.30"

// 支持任意精度、科學計數、三角函數等

2. 整數分位運算 (金融標準)


// 以「分」為單位存儲/計算,避免浮點數
const priceInCents = 1999; // 19.99 元
const totalCents = priceInCents * quantity; // 整數運算精確
const display = (totalCents / 100).toFixed(2); // 顯示時轉換

3. ES2020 BigInt (大整數)


// 適合超大整數運算,小數需自行縮放
const scale = 100n; // 兩位小數
const a = 1211n;    // 12.11 * 100
const b = 1222n;    // 12.22 * 100
const sum = (a + b) / scale; // 24.33n (BigInt 除法會截斷)
// 需手動處理小數點

性能基準測試 (百萬次運算)

方案相對耗時精度適用場景
原生 + - * /1x (基準)❌ 有誤差非關鍵計算、圖表展示
accAdd 縮放算法~3x✅ 精確簡單項目、無依賴要求
decimal.js~15x✅ 任意精度金融、科學計算、高精度需求
整數分位運算~1.2x✅ 精確電商價格、會計系統 (推薦)

總結建議

  1. 新項目金融/電商領域:整數分位運算 (存儲分、計算分、顯示元)
  2. 2. 通用工具庫場景:decimal.js 或 big.js (輕量版) 3. 簡單頁面無構建流程:accAdd 縮放函數 輕量無依賴 4. 避免直接使用原生浮點數進行金額計算
copyright © 萬盛學電腦網 all rights reserved