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
(1.005).toFixed(2) // "1.00" ❌ 應為 "1.01"(浮點數 1.005 實際略小)
// 解決:先縮放
Math.round(1.005 * 100) / 100 // 1.01 ✅
decimal.js、big.jsnum.toFixed(2) 配合 Number() 轉回數值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