Questions like: 7*0.8 JavaScript figure out is: 5.6000000000000005
The addition function, which is used to get the exact addition result.
Description: JavaScript addition results will be error, in two floating-point number added when it is more obvious. This function returns a more precise addition result.
Call: Accadd (ARG1,ARG2)
return value: Arg1 plus arg2 's exact result
function Accadd (arg1, arg2) {
var 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 (Math.max (R1, R2))
Return (ARG1 * m + arg2 * m)/M
}
Usage:
Adding an Add method to the number type is more convenient to call.
Number.prototype.add = function (ARG) {
Return Accadd (ARG, this);
}
Such as:
var T1 = 6.60;
var t2 = 1.32;
var t3 = 1.2;
var t4 = 1.2;
var T5 = 1.2;
Alert (number (T1). Add (number (t2)). Add (number (T3). Add (number (T4)). Add (number (T5)));
Subtraction function, which is used to obtain accurate subtraction results.
function Subtr (arg1, arg2) {
var 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 (Math.max (R1, r2));
Last modify by Deeka
Dynamic Control Precision Length
n = (r1 >= r2)? R1:R2;
Return ((ARG1 * M-ARG2 * m)/m). ToFixed (n);
}
multiplication function to get the exact result of the multiplication
Description: JavaScript multiplication results will be error, in two floating-point numbers are more obvious when multiplying. This function returns a more accurate result of the multiplication.
Call: Accmul (ARG1,ARG2)
return value: Arg1 times Arg2 's exact result
function Accmul (arg1, arg2) {
var 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 (M)
}
Usage:
Adding a Mul method to the number type is more convenient to call.
Number.prototype.mul = function (ARG) {
Return Accmul (ARG, this);
}
The Division function, which is used to get the exact division result
Description: JavaScript division results will be error, the two floating-point numbers are more obvious when dividing. This function returns a more precise division result.
Call: Accdiv (ARG1,ARG2)
Return value: Arg1 divided by Arg2 's exact result
function Accdiv (arg1, arg2) {
var t1 = 0, t2 = 0, R1, R2;
try {t1 = arg1.tostring (). Split (".") [1].length} catch (e) {}
try {t2 = arg2.tostring (). Split (".") [1].length} catch (e) {}
With (Math) {
R1 = number (arg1.tostring (). Replace (".", ""))
r2 = number (arg2.tostring (). Replace (".", ""))
Return (R1/R2) * POW (T2-T1);
}
}
Usage:
Adding a Div method to the number type is more convenient to call.