js precision floating point multiplication and division algorithm solution

Prone to problems when precision floating-point operations in js

1) division function

// Note: there will be error javascript division result, when the two floating-point division will be more obvious. This function returns the result of the division is more accurate. 
// Call: accDiv (arg1, arg2) 
// Return Value: arg1 arg2 exact result of dividing 


function accDiv (arg1, arg2) { 
    var T1 = 0, T2 = 0, R1, R2; 
    the try {T1 = arg1.toString () .split ( ".") [1] .length} catch (e) {} // - length after the decimal point
    . ( ".") try { t2 = arg2.toString () split [1] .length } catch (e) {} // - length after the decimal point
    with (the Math) { 
      R1 = Number the (arg1.toString () Replace (, ""). ".") // - decimal points removed integer
      r2 = Number (. "." arg2.toString ( ) replace (, "")) // - integer decimal points removed
      return (r1 / r2) * pow (10, t2-t1); // --- integer division multiplied by the square of the length of 10 decimal
    } 


2) multiplication function

// Description: javascript multiplication result there will be errors, when two floating-point multiply more obvious. This function returns the more accurate the multiplication result. 
// Call: accMul (arg1, arg2) 
// Return value: accurate results arg1 arg2 multiplying the 
function accMul (arg1, arg2) { 
    var m = 0, S1 = arg1.toString (), S2 = arg2.toString () ; 
    the try {m + = s1.split ( ".") [. 1]} .length the catch (E) {} 
    the try {m + = s2.split ( ".") [. 1]} .length the catch (E) {} 
    return Number The (s1.replace ( ".", "")) * Number The (s2.replace ( ".", "")) / Math.pow (10, m) 


3) addition function

// Description: javascript the addition result will be errors, when two floating point adding more obvious. This function returns the result of more accurate addition. 
// Call: accAdd (arg1, arg2) 
// Return Value: arg1 arg2 accurate results of adding 
function accAdd (arg1, arg2) { 
    var R1, R2, m; 
    . Arg1.toString the try {R1 = () Split ( " . ") [. 1]} .length the catch (E) R1 = {0} 
    the try {arg2.toString R2 = (). Split (". ") [. 1]} .length the catch (E) R2 = {0} 
    m Math.pow = (10, Math.max (R1, R2)) 
    return (arg1 arg2 * * m + m) / m 

4) the subtraction function

function accSub(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(10,Math.max(r1,r2)); 
       //last modify by deeka 
       //动态控制精度长度 
       n=(r1>=r2)?r1:r2; 
       return ((arg1*m-arg2*m)/m).toFixed(n); 
}

Guess you like

Origin www.cnblogs.com/tongshuangxiong/p/11200899.html