Connor Seiler
Connor Seiler

Reputation: 19

C# Operator '*' cannot be applied to operands of type 'double' and 'decimal'

A couple errors I am struggling to understand. I am attempting to make a sales tax calculator. But keep getting operation error because I cannot multiply a decimal by decimal. Here is my code for my calulate button:

decimal decTax;
decimal decTotal;
string input;
decimal decOrder;
// Accept the order from the Console window
Console.Write("Enter order in dollars: $");
input = Console.ReadLine();
Decimal.TryParse(input, out decOrder);

// Calculate the sales tax
decTax = (0.06D  * (decOrder + decTax));
decTotal = (decOrder + decTax);
// Write the results to the Console Window
Console.WriteLine();
Console.WriteLine("The Total is " & decTotal.ToString("c"));
Console.ReadLine();

Upvotes: 1

Views: 3533

Answers (3)

Bozhidar Iliev
Bozhidar Iliev

Reputation: 1

VS throws the same error message in different scenarios of the same error, so what the problem could be, doesn't become immediately obvious from the answers posted so far. You get this error if:

  1. One or more of the multiplied values is not decimal or cast to deicmal.
  2. The variable that's supposed to store the result is not explicitly decimal.(This one is so obvious it's actually hard to spot sometimes. I recently had such a case - the variable was declared as double which obviously can't store a decimal value and since the error message is about the operands being multiplied it took me some time to notice why it didn't go away after casting the double operand to decimal)

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

The error is exactly what it says. You can't multiply a decimal by your literal double 0.06D. The reason why you can't do that implicitly is because converting a decimal to a double can result in a lose of precision. The compiler won't make an automatic conversion if there is a possibility of losing precision.

Try casting it to a decimal too:

decTax = ((decimal)0.06 * (decOrder + decTax));

Or you can use the m suffix to indicate that your literal is a decimal and not a double:

decTax = 0.06m * (decOrder + decTax));

Note, however, in the code you posted in your question you never assigned an initial value to decTax. So decOrder + decTax can't be calculated. It's unclear from your question what you intended decTax to be in that case, but it needs an initial value.

Upvotes: 4

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

D means Double for Decimal use M.

decTax = (0.06M  * (decOrder + decTax));

Refer to this documentation for more information.

Upvotes: 1

Related Questions