方法 1:通过 toFixed() 格式化数字
let result = (0.1 + 0.2).toFixed(2); // 保留两位小数
console.log(result); // 输出 "0.30"
注意:toFixed 会返回字符串。如果需要数值类型,可以通过 parseFloat 转回数值:
let result = parseFloat((0.1 + 0.2).toFixed(2));
console.log(result); // 输出 0.3
方法 2:将浮点数转为整数计算
通过将浮点数放大到整数进行运算,然后再缩小回来:
function add(a, b) {
let factor = Math.pow(10, Math.max(decimalPlaces(a), decimalPlaces(b)));
return (a * factor + b * factor) / factor;
}
function decimalPlaces(num) {
const str = num.toString();
if (str.includes('.')) {
return str.split('.')[1].length;
}
return 0;
}
// 示例
console.log(add(0.1, 0.2)); // 输出 0.3
方法 3:使用第三方库
一些库专门解决了 JavaScript 浮点数计算的精度问题,例如:
- Big.js
const Big = require('big.js');
let result = Big(0.1).plus(0.2);
console.log(result.toString()); // 输出 "0.3"
- Decimal.js
const Decimal = require('decimal.js');
let result = new Decimal(0.1).plus(0.2);
console.log(result.toString()); // 输出 "0.3"
方法 4:手动实现加、减、乘、除的精度修复
// 获取两个数字的小数位数
function getDecimalLen(num) {
const parts = num.toString().split('.');
return parts[1] ? parts[1].length : 0;
}
// 精确加法
function preciseAdd(a, b) {
const factor = Math.pow(10, Math.max(getDecimalLen(a), getDecimalLen(b)));
return (a * factor + b * factor) / factor;
}
// 精确减法
function preciseSubtract(a, b) {
const factor = Math.pow(10, Math.max(getDecimalLen(a), getDecimalLen(b)));
return (a * factor - b * factor) / factor;
}
// 精确乘法
function preciseMultiply(a, b) {
const factorA = Math.pow(10, getDecimalLen(a));
const factorB = Math.pow(10, getDecimalLen(b));
return (a * factorA) * (b * factorB) / (factorA * factorB);
}
// 精确除法
function preciseDivide(a, b) {
const factorA = Math.pow(10, getDecimalLen(a));
const factorB = Math.pow(10, getDecimalLen(b));
return (a * factorA) / (b * factorB);
}
// 示例
console.log(preciseAdd(0.1, 0.2)); // 输出 0.3
console.log(preciseSubtract(0.3, 0.1)); // 输出 0.2
console.log(preciseMultiply(0.1, 0.2)); // 输出 0.02
console.log(preciseDivide(0.3, 0.1)); // 输出 3