C # Compare two doubles with .Equals ()

I use ReShaper, and when I compare two double values ​​with ==, this suggests that I should use Math. ABS with tolerance. See: https://www.jetbrains.com/help/resharper/2016.2/CompareOfFloatsByEqualityOperator.html

In this example

double d = 0.0;
double d2 = 0.0;
if (d == d2)
{
    /* some code */
}

then converted to

double d = 0.0;
double d2 = 0.0;
if (Math.Abs(d - d2) < TOLERANCE)
{
    /* some code */
}

But I think it’s really hard for the developer to think about the right tolerance. Therefore, I thought that this could be implemented in the Double.Equals () method.

But this method is implemented like this

public override bool Equals(Object obj) {
    if (!(obj is Double)) { 
        return false;
    } 
    double temp = ((Double)obj).m_value; 
    // This code below is written this way for performance reasons i.e the != and == check is intentional.
    if (temp == m_value) { 
        return true;
    }
    return IsNaN(temp) && IsNaN(m_value);
}

public bool Equals(Double obj)
{ 
    if (obj == m_value) {
        return true; 
    } 
    return IsNaN(obj) && IsNaN(m_value);
}

Why? And what is the correct way to compare double values?

+4
source share
1 answer

You can create an extension method

public static class DoubleExtension 
{
    public static bool AlmostEqualTo(this double value1, double value2)
    {
        return Math.Abs(value1 - value2) < 0.0000001; 
    }
}

And use it like this

doubleValue.AlmostEqualTo(doubleValue2)
+3
source

Source: https://habr.com/ru/post/1661047/


All Articles