我记得刚开始学js的时候学到浮点有举例0.1+0.2 它的计算结果是:
0.1+0.2
0.30000000000000004
很神奇的一个计算,js是弱语言,在精度上没做处理;
我就自己定义了加减乘除:
加:
export const accAdd = (arg1, arg2) => {
let r1, r2, m;
try {
r1 = arg1.toString().split('.')[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split('.')[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
return (arg1 * m + arg2 * m) / m;
};
减
export function accSub(arg1, arg2) {
let r1, r2, m, n;
try {
r1 = arg1.toString().split('.')[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split('.')[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
//动态控制精度长度
n = r1 >= r2 ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(2);
}
乘
export const accMul = (arg1, arg2) => {
let m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split('.')[1].length;
} catch (e) {}
try {
m += s2.split('.')[1].length;
} catch (e) {}
return (
(Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) /
Math.pow(10, m)
);
};
除
export function accDiv(arg1, arg2) {
let t1 = 0,
t2 = 0,
r1,
r2;
try {
t1 = arg1.toString().split('.')[1].length;
} catch (e) {}
try {
t2 = arg2.toString().split('.')[1].length;
} catch (e) {}
r1 = Number(arg1.toString().replace('.', ''));
r2 = Number(arg2.toString().replace('.', ''));
return (r1 / r2) * Math.pow(10, t2 - t1);
}
这和网上搜出来的
(num1* 100 + num2* 100) / 100
去控制两位小数相加基础上去写;
每天都在打代码中学习