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
Number (64 位雙精度浮點數)。/**
* 精確四則運算:放大為整數運算,再縮小
* @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。"123.45",前端 new Decimal(str) 還原,避免精度損失。