Example 1
The basic idea is to turn the floating-point numbers into integers and divide them by the N-order of the equivalent 10. n is (the sum of the back lengths of two floating-point numbers).
code is as follows |
copy code |
function FXF (f1, F2) { f1 + = '; F2 + + '; var f1len = f1.spli T ('. ') [1].length, f2len = F2.split ('. ') [1].length; if (f1len) { f1 = F1.replace ('. ', '); & nbsp; } if (f2len) { F2 = F2.replace ('. ', ' ); } Return F1 * F2/MATH.POW (F1len + F2len); }; |
Example 2
The code is as follows |
Copy Code |
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) } Adding a Mul method to the number type is more convenient to call. Number.prototype.mul = function (ARG) { Return Accmul (ARG, this); } |
The precision problem of additional method
The code is as follows |
Copy Code |
/Description: JavaScript addition results will be error, in addition to two floating-point numbers will be 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 } Adding an Add method to the number type is more convenient to call. Number.prototype.add = function (ARG) { Return Accadd (ARG, this); } |