js decimal calculation accuracy lose

The reason: the calculation will be converted into binary decimal precision is lost 

For example: N-th power of 4.02 * 10 count how is wrong; FAQ 0.1 + 0.2 = 0.3!. . .

Processing: calculated decimal conversion

// addition

function addNum (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)),(multiNum(a,e) + multiNum(b,e)) / e;
}
    
// subtraction
    
function subNum (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)),(multiNum(a,e) - multiNum(b,e)) / e; 
}
// multiplication

Function multiNum (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);
}

 // division

function divide (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(".","")),this.mul(c / d,Math.pow(10,f - e));
}

 

Guess you like

Origin www.cnblogs.com/zui1024/p/12557992.html