0

I have an if statement like this

decimal var1, var2;
if(var1 == 0.00 || var2 == 0.00)
{
  ...
} 

Compiler shows error:

Operator '==' cannot be applied to operands of type 'decimal' and 'double'

I have also tried

If(var1 = 0.00 || var2 = 0.00){
  //this
}

Compiler shows error:

Operator '||' cannot be applied to operands of type 'decimal' and 'double'

And the third thing i did was make 0.00 a string like "0.00" In both the previous methods just to see if it would do anything different.

  • 2
    You've got the answer probably. But FWIW you shouldn't compare floating point with `==` or `!=`. For decimal that's fine. Refer [this](http://stackoverflow.com/questions/1398753/comparing-double-values-in-c-sharp) – Sriram Sakthivel Nov 13 '14 at 15:36
  • 1
    Side note: please post complete compile error messages... Which should be something like very self explanatory "Operator '==' cannot be applied to operands of type 'decimal' and 'double'" in this case. – Alexei Levenkov Nov 13 '14 at 15:42
  • I will make sure I do that from now on, I will add it to this just to make it more helpful for anyone looking at this in the future. – RyeNyeTheComputerScienceGuy Nov 13 '14 at 15:45

1 Answers1

9

0.00 is treated as double.You can't use == operator with double and decimal directly. You need to cast the values to decimal or use m literal to make the compiler treat is as decimal instead:

if(var1 == 0.00m || var2 == 0.00m)
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • +1. Note that similar behavior will happen for all comparison between any types that don't have [Implicit Numeric Conversion](http://msdn.microsoft.com/en-us/library/y5b434w4.aspx) between each other. – Alexei Levenkov Nov 13 '14 at 15:58