自定义方法
const exactNumber = {
/**
* 求和
*/
sum: function accAdd(num1: number, num2: number) {
let r1; let r2; let
m;
try {
r1 = num1.toString().split('.')[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = num2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2)); // pow() 方法可返回 x 的 y 次幂的值。
// return (num1*m+num2*m)/m;
return Math.round(num1 * m + num2 * m) / m; // round() 方法可把一个数字舍入为最接近的整数。然后除以10的N次方
},
/**
* 求差
*/
sub: function accSub(arg1: number, arg2: number) {
let r1; let r2; let m; let
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));
// last modify by deeka
// 动态控制精度长度
n = (r1 >= r2) ? r1 : r2;
return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
},
/**
* 求积
*/
pro: function accMul(arg1: number, arg2: number, decimal?: number) {
let m = 0;
const s1 = arg1.toString();
const s2 = arg2.toString();
try {
m += s1.split(".")[1].length
} catch (e) { }
try {
m += s2.split(".")[1].length
} catch (e) { }
let result = Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); // pow() 方法可返回 x 的 y 次幂的值
if (decimal || decimal === 0) {
result = Number(result.toFixed(decimal));
}
return result
},
/**
* 求商
*/
quo: function accDiv(arg1: number, arg2: number, decimal?: | number) {
let t1 = 0;
let t2 = 0;
let r1; let
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)*pow(10,t2-t1); //改变这一句,这里相当于又是乘法了 so改变一下
let result = this.pro(r1 / r2, Math.pow(10, t2 - t1)) // 调取乘法函数
if (decimal || decimal === 0) {
result = Number(result.toFixed(decimal));
}
return result;
}
}
export default exactNumber;
第三方库decimal.js