[removed] Comparing two float values

前端 未结 4 1802
忘了有多久
忘了有多久 2020-12-09 01:55

I have this JavaScript function:

Contrl.prototype.EvaluateStatement = function(acVal, cfVal) {

    var cv = parseFloat(cfVal).toFixed(2);
    var av = parse         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 02:45

    Compare float numbers with precision:

    var precision = 0.001;
    
    if (Math.abs(n1 - n2) <= precision) {
      // equal
    }
    else {
      // not equal
    }
    

    UPD: Or, if one of the numbers is precise, compare precision with the relative error

    var absoluteError = (Math.abs(nApprox - nExact)),
      relativeError = absoluteError / nExact;
    
    return (relativeError <= precision);
    

提交回复
热议问题