How do I find if two variables are approximately equals?

后端 未结 5 1254
夕颜
夕颜 2020-12-03 16:44

I am writing unit tests that verify calculations in a database and there is a lot of rounding and truncating and stuff that mean that sometimes figures are slightly off.

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 17:27

    You could provide a function that includes a parameter for an acceptable difference between two values. For example

    // close is good for horseshoes, hand grenades, nuclear weapons, and doubles
    static bool CloseEnoughForMe(double value1, double value2, double acceptableDifference)
    {
        return Math.Abs(value1 - value2) <= acceptableDifference; 
    }
    

    And then call it

    double value1 = 24.5;
    double value2 = 24.4999;
    
    bool equalValues = CloseEnoughForMe(value1, value2, 0.001);
    

    If you wanted to be slightly professional about it, you could call the function ApproximatelyEquals or something along those lines.

    static bool ApproximatelyEquals(this double value1, double value2, double acceptableDifference)
    

提交回复
热议问题