3

Possible Duplicate:
C#, Operator ‘*’ cannot be applied to operands of type ‘double’ and ‘decimal’

Hi i want to Multiply the value that inserted in the textbox but i getting error. Here's my Code.

decimal num1, num2;
if(decimal.TryParse(textBox1.Text, out num1) 
   && decimal.TryParse(textBox2.Text, out num2)){

 decimal ans = num1 * 0.20 + num2 * 0.20;
 Label1.Text = ans.ToString();

        }else{
            MessageBox.Show("Please Put a number!! ");
        }

I'm having error in "ans" please help me. This my error "Operator * cannot be applied to operands of type 'decimal' and double;"

Community
  • 1
  • 1
Jay
  • 137
  • 2
  • 5
  • 12
  • Jay, what is the error message? – Zbigniew Nov 11 '12 at 10:13
  • Operator * cannot be applied to operands of type 'decimal' and double; – Jay Nov 11 '12 at 10:14
  • 1
    Then, this is a duplicate of [http://stackoverflow.com/questions/363706/c-operator-cannot-be-applied-to-operands-of-type-double-and-decimal](http://stackoverflow.com/questions/363706/c-operator-cannot-be-applied-to-operands-of-type-double-and-decimal) – Zbigniew Nov 11 '12 at 10:16

2 Answers2

3

The problem is that the compiler sees the constants as Double.
To fix the error itself you can either cast the constants to decimal like this:

decimal ans = num1 * (decimal)0.20 + num2 * (decimal)0.20;

Or even better (as stated in the comments) you can just specify the type of the constants

decimal ans = num1 * 0.20m + num2 * 0.20m;
Community
  • 1
  • 1
Blachshma
  • 17,097
  • 4
  • 58
  • 72
  • 1
    Why casting constants instead of [making them of the right type](http://stackoverflow.com/a/166762/11683) in the first place? It may even [be harmful](http://stackoverflow.com/questions/166752/c-sharp-compiler-number-literals/166762#comment6475244_166809). – GSerg Nov 11 '12 at 10:19
  • GSerg is right, no casting needed. Look what Hamlet Hakobyan wrote – CSharpie Nov 11 '12 at 10:27
2
decimal ans = num1 * 0.20m + num2 * 0.20m;
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68