Compare a double to a float?

  • Thread starter Thread starter Andrew Murray
  • Start date Start date
A

Andrew Murray

Is it possible to compare a double with a float in c# without casting to
one of the types first?

It appears you cannot...


float num = 1.545f;
double dnum = 1.545;

if (dnum == num)
{
Console.WriteLine("You can");
}
else
{
Console.WriteLine("You cant");
}
 
Andrew,

No, you can not. It's like apples and oranges, you can't compare. You
have to convert one to the other before you compare.

Hope this helps.
 
In addition to what Nicholas said, it almost never makes
sense to compare floating point variables for equality.
Instead, check if the difference is smaller than some value,
e.g.:

if (Math.Abs(num1 - num2) < 0.001)
....

- Magnus
 
Magnus Krisell said:
In addition to what Nicholas said, it almost never makes
sense to compare floating point variables for equality.
Instead, check if the difference is smaller than some value,
e.g.:

if (Math.Abs(num1 - num2) < 0.001)

To refine this, the threshold for equality should be related to the size of
the numbers being compared. If num1 is .00002 and num2 is .001, they're
equal to zero significant digits, but they will satisfy the condition above.
If num1 is 6.123456 * 10**23 and num2 is 6.123457 * 10**23, they're equal to
6 significant digits, but don't satisfy it.
 
Back
Top