Quick Solution to Error Problem of js Digital Calculation
- 2021-07-24 09:50:03
- OfStack
Examples are as follows:
// Addition function, which is used to get accurate addition results
// Description: javascript There will be errors in the addition results of two floating-point numbers, which will be obvious when two floating-point numbers are added. This function returns a more accurate addition result.
// Call: accAdd(arg1,arg2)
// Return value: arg1 Plus arg2 Accurate results of
function add(a,b){
var c, d, e;
try {
c = a.toString().split(".")[1].length;
} catch (f) {
c = 0;
}
try {
d = b.toString().split(".")[1].length;
} catch (f) {
d = 0;
}
return e = Math.pow(10, Math.max(c, d)), (mul(a, e) + mul(b, e)) / e;
}
// Multiplication function, which is used to get accurate multiplication results
// Description: javascript There will be errors in the multiplication results of two floating-point numbers, which will be obvious when two floating-point numbers are multiplied. This function returns a more accurate multiplication result.
// Call: accMul(arg1,arg2)
// Return value: arg1 Multiply by arg2 Accurate results of
function mul(a, b) {
var c = 0,
d = a.toString(),
e = b.toString();
try {
c += d.split(".")[1].length;
} catch (f) {}
try {
c += e.split(".")[1].length;
} catch (f) {}
return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}
// Subtraction function, which is used to obtain accurate subtraction results
// Description: javascript There will be errors in the subtraction results of, which will be obvious when two floating-point numbers are added. This function returns more accurate subtraction results.
// Call: accSubtr(arg1,arg2)
// Return value: arg1 Subtract arg2 Accurate results of
function sub(a,b){
var c, d, e;
try {
c = a.toString().split(".")[1].length;
} catch (f) {
c = 0;
}
try {
d = b.toString().split(".")[1].length;
} catch (f) {
d = 0;
}
return e = Math.pow(10, Math.max(c, d)), (mul(a, e) - mul(b, e)) / e;
}
// Division function, which is used to get accurate division results
// Description: javascript There will be errors in the division results of two floating-point numbers, which will be obvious when dividing two floating-point numbers. This function returns a more accurate division result.
// Call: accDiv(arg1,arg2)
// Return value: arg1 Divide by arg2 Accurate results of
function div(a, b) {
var c, d, e = 0,
f = 0;
try {
e = a.toString().split(".")[1].length;
} catch (g) {}
try {
f = b.toString().split(".")[1].length;
} catch (g) {}
return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), mul(c / d, Math.pow(10, f - e));
}