0.1 + 0.2; // 0.30000000000000004 ❌
12.11 + 12.22; // 24.330000000000002 ❌
原因:IEEE 754 雙精度浮點數無法精確表示十進制小數,二進制表示存在無限循環。
/**
* 精確加法
* @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
// 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"
// 支持任意精度、科學計數、三角函數等
// 以「分」為單位存儲/計算,避免浮點數
const priceInCents = 1999; // 19.99 元
const totalCents = priceInCents * quantity; // 整數運算精確
const display = (totalCents / 100).toFixed(2); // 顯示時轉換
// 適合超大整數運算,小數需自行縮放
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 | ✅ 精確 | 電商價格、會計系統 (推薦) |