JS 只有一種數字型別 Number(64 位雙精度)。許多十進位小數無法用二進位有限位數精確表示:
0.1 → 0.0001100110011... (循環)
0.2 → 0.001100110011...
0.3 → 0.010011001100...
因此 0.1 + 0.2 === 0.3 為 false(實際為 0.30000000000000004)。
1.0 - 0.9 === 0.1 // false (0.09999999999999998)
1.0 - 0.8 === 0.2 // false
1.0 - 0.7 === 0.3 // false
0.1 + 0.2 === 0.3 // false
0.28 * 100 === 28 // false (28.000000000000004)
parseFloat((1.0 - 0.9).toFixed(10)) === 0.1; // true
// toFixed(10) 保留 10 位小數並四捨五入,parseFloat 去除尾隨零
缺點: 字串轉換開銷、需預知精度、大數字可能科學記號法。
// 以「分」為單位儲存/計算,顯示時除 100
const price1 = 199; // $1.99
const price2 = 299; // $2.99
const totalCents = price1 + price2; // 498
const total = totalCents / 100; // 4.98
// 通用工具
const Currency = {
toCents(yuan) { return Math.round(yuan * 100); },
fromCents(cents) { return cents / 100; },
add(a, b) { return Currency.fromCents(Currency.toCents(a) + Currency.toCents(b)); },
mul(a, b) { return Currency.fromCents(Math.round(Currency.toCents(a) * Currency.toCents(b) / 100)); }
};
Currency.add(0.1, 0.2); // 0.3 ✅
function floatEquals(a, b, epsilon = Number.EPSILON) {
return Math.abs(a - b) < epsilon;
}
floatEquals(0.1 + 0.2, 0.3); // true
floatEquals(1.0 - 0.9, 0.1); // true
注意: Number.EPSILON (2.22e-16) 適合單位量級比較,大數字需放大 epsilon。
import Decimal from "decimal.js";
new Decimal(0.1).plus(0.2).equals(0.3); // true
new Decimal(1.0).minus(0.9).equals(0.1); // true
// 任意精度、無精度損失、支援科學記號、模數、開根號等
| 場景 | 推薦方案 |
|---|---|
| 一般顯示格式化 | num.toFixed(2) / Intl.NumberFormat |
| 金額計算(電商、金融) | **整數分單位** 或 decimal.js |
| 科學計算/高精度需求 | decimal.js / big.js |
| 簡單比較 | Math.abs(a-b) < Number.EPSILON * Math.max(1, Math.abs(a), Math.abs(b)) |
Number.prototype.equals = function(n, eps = Number.EPSILON) {
return Math.abs(this - n) < eps * Math.max(1, Math.abs(this), Math.abs(n));
};
(0.1 + 0.2).equals(0.3); // true
警告: 污染原型鏈可能衝突,庫/框架代碼中禁用。