1

please see my below code and double comparison not working properly, though i have cast, double.Equal() method used, but no result. giving false

double b;
b = (1.6 + 1.6 + 1.6) / 3.0;

if( b == 1.6d)
{
     Console.WriteLine("True");
}
else
{
     Console.WriteLine("False");
}

// if( b.Equal(1.6))  -- No Result
mason
  • 31,774
  • 10
  • 77
  • 121
sebu
  • 2,824
  • 1
  • 30
  • 45
  • This is a common problem with double comparisons This is a good answer: http://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison – Display name Apr 28 '17 at 19:11
  • 1
    An option would be to change your `double` to `decimal` if you're open too that solution. – I.B Apr 28 '17 at 19:13

1 Answers1

3

Because actual result value of operation (1.6 + 1.6 + 1.6) / 3.0 is 1.6000000000000003.

You need to use like:

if(Math.Abs(1.6d - value) < TOLERANCE)
{
     Console.WriteLine("True");
}
else
{
     Console.WriteLine("False");
}

And define acceptable tolerance.

Have a look at 0.30000000000000004.com

Andrii Litvinov
  • 12,402
  • 3
  • 52
  • 59