JS数字精度丢失的原因及解决方案
大纲
1.了解原因
2.解决方案
1.原因
因为在计算机中,数字先转二进制,然后运算,最后转十进制
例如:0.1 + 0.2
0.1 也就是0.0001100110011001100110011001100110011001100110011001101
0.2 也就是0.001100110011001100110011001100110011001100110011001101
即:
0.00011001100110011001100110011001100110011001100110011010 +
0.0011001100110011001100110011001100110011001100110011010 =
0.0100110011001100110011001100110011001100110011001100111
结果0.0100110011001100110011001100110011001100110011001100111再转换成十进制就是0.30000000000000004。
2.解决办法
(1)插件Decimal
0.1 + 0.2 // 0.30000000000000004
x = new Decimal(0.1)
y = x.plus(0.2) // '0.3'
(2)插件bignumber
x = new BigNumber(0.1)
y = x.plus(0.2)
(3)变成整数
function add(num1, num2) {
const num1Len = (num1.toString().split('.')[1] ).length;
const num2Len = (num2.toString().split('.')[1] ).length;
const maxLen = Math.pow(10, Math.max(num1Len, num2Len));
return (num1 * maxLen + num2 * maxLen) / maxLen;
}