Comparing floating point values

The following extension methods may be useful to implement Kevin’s suggestion:

public static bool IsEqualTo(this double a, double b, double margin)
{
    return Math.Abs(a - b) < margin;
}

public static bool IsEqualTo(this double a, double b)
{
    return Math.Abs(a - b) < double.Epsilon;
}

So now you can just do:

if(x1.IsEqualTo(x2)) ...
if(x1.IsEqualTo(x2, 0.01)) ...

Just change the IsEqualTo to a more appropriate name, or change the default margin to anything better than double.Epsilon, if needed.

Leave a Comment