Avoiding problems with JavaScript's weird decimal calculations

后端 未结 6 677
我寻月下人不归
我寻月下人不归 2020-11-29 05:13

I just read on MDN that one of the quirks of JS\'s handling of numbers due to everything being \"double-precision 64-bit format IEEE 754 values\" is that when you d

6条回答
  •  情深已故
    2020-11-29 05:27

    You need a bit of error control.

    Make a little double comparing method:

    int CompareDouble(Double a,Double b) {
        Double eplsilon = 0.00000001; //maximum error allowed
    
        if ((a < b + epsilon) && (a > b - epsilon)) {
            return 0;
        }
        else if (a < b + epsilon)
            return -1;
        }
        else return 1;
    }
    

提交回复
热议问题