js 计算失精是因为js 先将10十进制代码转化为2进制,再计算导致
具体解决方案:
1. 加
function accAdd(arg1,arg2){
var r1,r2,m;
try{r1=arg1.toString().split(".")[].length}catch(e){r1=}
try{r2=arg2.toString().split(".")[].length}catch(e){r2=}
m=Math.pow(,Math.max(r1,r2))
return (arg1*m+arg2*m)/m
}
2. 减
function Subtr(arg1,arg2){
var r1,r2,m,n;
try{r1=arg1.toString().split(".")[].length}catch(e){r1=}
try{r2=arg2.toString().split(".")[].length}catch(e){r2=}
m=Math.pow(,Math.max(r1,r2));
n=(r1>=r2)?r1:r2;
return ((arg1*m-arg2*m)/m).toFixed(n);
}
更新:
个别情况, 加减依旧有问题, 更新如下:
//加
function accAdd(arg1, arg2) {
var r1,
r2,
m,
num1,
num2;
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));
num1 = r1 == 0? parseInt(arg1 * m): (parseInt(`${arg1.toString().replace('.', '')}`)*m/(Math.pow(10, r1)));
num2 = r2 == 0? parseInt(arg2 * m): (parseInt(`${arg2.toString().replace('.', '')}`)*m/(Math.pow(10, r2)));
return (num1 + num2) / m;
} //减 function Subtr(arg1, arg2) {
var r1,
r2,
m,
n,
num1,
num2;
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;
num1 = r1 == 0? parseInt(arg1 * m): (parseInt(`${arg1.toString().replace('.', '')}`)*m/(Math.pow(10, r1)));
num2 = r2 == 0? parseInt(arg2 * m): (parseInt(`${arg2.toString().replace('.', '')}`)*m/(Math.pow(10, r2)));
return ((num1 - num2) / m).toFixed(n);
}
3.乘
function accMul(arg1,arg2) {
var m=,s1=arg1.toString(),s2=arg2.toString();
try{m+=s1.split(".")[].length}catch(e){}
try{m+=s2.split(".")[].length}catch(e){}
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(,m)
}
4.除
function accDiv(arg1,arg2){
var t1 = , t2 = , r1, r2;
try {
t1 = arg1.toString().split(".")[].length
} catch (e) {}
try {
t2 = arg2.toString().split(".")[].length
} catch (e) {}
r1 = Number(arg1.toString().replace(".", ""))
r2 = Number(arg2.toString().replace(".", ""))
return getMultiFormat((r1 / r2), Math.pow(, t2 - t1));
}