1 year ago

#36345

test-img

alrts

Comparing decimal values of two variables of different types do not detect equality in all cases

I recently detected the hard way that in the comparison in Visual Studio C#

double a = 0.4;
float b = 0.4f;
if (a < b) break;

a turns out to be smaller than b, so the comparison is true and the program branches out. This came to me as a surprise.

I have an idea why this is so, namely because the conversion of the decimal values to zeroes and ones is different for float and double types.

I would expect from a compiler that when equality comes into play, it will double check whether the literal representation of the decimal values happen to be identical and then bring the correct result. Or is this exactly what the compiler cannot do for some reason? Would it be possible at least to issue a warning at run time?

Of course, one solution to the problem is

if (a < (double)b) break;

and in this case the comparison is evaluated correctly. Can I tell the compiler to do that for me?

c#

types

equality

comparison-operators

data-representation

0 Answers

Your Answer

Accepted video resources