问题描述
在 JavaScript
中整数和浮点数都属于 Number
数据类型,均以 64 位浮点数形式储存。浮点数在进行四则运算时常常会发现出现精度问题,在浏览器控制台试验如下所示:
> 0.1+0.2
< 0.30000000000000004
> 0.3-0.2
< 0.09999999999999998
> 19.9*100
< 1989.9999999999998
> 0.3/0.1
< 2.9999999999999996
解决方案
封装自己的四则运算函数解决浮点数计算精度问题,主要思路是先转换成整数进行计算再转换成对应的精度,源代码如下所示:
1.加法
Math.max(len1, len2)
表示返回len1
,len2
二者中的较大值;
Math.pow(10, max)
表示返回10
的max
次方。
function add (arg1, arg2) {
const len1 = (arg1.toString().split('.')[1] || '').length;
const len2 = (arg2.toString().split('.')[1] || '').length;
const max = Math.max(len1, len2);
const base = Math.pow(10, max);
return (Number(arg1) * base + Number(arg2) * base) / base;
}
2.减法
function sub (arg1, arg2) {
const len1 = (arg1.toString().split('.')[1] || '').length;
const len2 = (arg2.toString().split('.')[1] || '').length;
const max = Math.max(len1, len2);
const base = Math.pow(10, max);
return (Number(arg1) * base - Number(arg2) * base) / base;
}
3.乘法
function mul (arg1, arg2) {
const len1 = (arg1.toString().split('.')[1] || '').length;
const len2 = (arg2.toString().split('.')[1] || '').length;
const base1 = Math.pow(10, len1);
const base2 = Math.pow(10, len2);
const base = Math.pow(10, len1 + len2);
return ((Number(arg1) * base1) * (Number(arg2) * base2)) / base;
}
4.除法
function div (arg1, arg2) {
const len1 = (arg1.toString().split('.')[1] || '').length;
const len2 = (arg2.toString().split('.')[1] || '').length;
const base1 = Math.pow(10, len1);
const base2 = Math.pow(10, len2);
const base = Math.pow(10, len1 + len2);
return ((Number(arg1) * base1) / (Number(arg2) * base2)) / base;
}
验证
// test
console.log('original: 0.1 + 0.2 = ', 0.1 + 0.2);
console.log('revised : 0.1 + 0.2 = ', add(0.1, 0.2));
console.log('\n');
console.log('original: 0.3 - 0.2 = ', 0.3 - 0.2);
console.log('revised : 0.3 - 0.2 = ', sub(0.3, 0.2));
console.log('\n');
console.log('original: 19.9 * 100 = ', 19.9 * 100);
console.log('revised : 19.9 * 100 = ', mul(19.9, 100));
console.log('\n');
console.log('original: 0.3 / 0.1 = ', 0.3 / 0.1);
console.log('revised : 0.3 / 0.1 = ', div(0.3, 0.1));
运行结果如下所示: