I use ReShaper and when I compare two double values with ==, it suggests that I should use the Math. ABS method with a tolerance. See: https://www.jetbrains.com/help/resharper/2016.2/CompareOfFloatsByEqualityOperator.html
This example
double d = 0.0;
double d2 = 0.0;
if (d == d2)
{
/* some code */
}
is 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 complicated for a developer to think about the right tolerance. So I thought this may be implemented in the Double.Equals() method.
But this method is implemented like so
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 is that? And what is the correct way to compare double values?
You could 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With