This code was used by the project before. I found this code online before, but there will still be bugs in division and addition operations under specific conditions. I have made some optimizations on this.
Copy the codeThe code is as follows:
//Divide function is used to obtain accurate division results
//Note: There will be errors in the division result of javascript, which will be more obvious when dividing two floating point numbers. This function returns a more accurate division result.
//Call: accDiv(arg1,arg2)
//Return value: the exact result of arg1 divided by arg2
function accDiv(arg1, arg2) {
var t1 = 0, t2 = 0, r1, r2;
try { t1 = ().split(".")[1].length } catch (e) { }
try { t2 = ().split(".")[1].length } catch (e) { }
with (Math) {
r1 = Number(().replace(".", ""))
r2 = Number(().replace(".", ""))
return accMul((r1 / r2),pow(10, t2 - t1));
}
}
Copy the codeThe code is as follows:
//Multiple function is used to obtain accurate multiplication results
//Note: There will be errors in the multiplication result of javascript, which will be more obvious when multiplying two floating point numbers. This function returns a more accurate multiplication result.
//Call: accMul(arg1,arg2)
//Return value: the exact result of arg1 multiplied by arg2
function accMul(arg1, arg2) {
var m = 0, s1 = (), s2 = ();
try { m += (".")[1].length } catch (e) { }
try { m += (".")[1].length } catch (e) { }
return Number((".", "")) * Number((".", "")) / (10, m)
}
Copy the codeThe code is as follows:
//Intermediate solution to addition operation
function accAdd(arg1, arg2) {
var r1, r2, m, c;
try { r1 = ().split(".")[1].length } catch (e) { r1 = 0 }
try { r2 = ().split(".")[1].length } catch (e) { r2 = 0 }
c = (r1 - r2);
m = (10, (r1, r2))
if (c > 0) {
var cm = (10, c);
if (r1 > r2) {
arg1 = Number(().replace(".", ""));
arg2 = Number(().replace(".", "")) * cm;
}
else {
arg1 = Number(().replace(".", "")) * cm;
arg2 = Number(().replace(".", ""));
}
}
else {
arg1 = Number(().replace(".", ""));
arg2 = Number(().replace(".", ""));
}
return accDiv((arg1 + arg2),m);
}