Reputation: 19
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
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:
Upvotes: 0
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
Reputation: 33381
D
means Double
for Decimal
use M
.
decTax = (0.06M * (decOrder + decTax));
Refer to this documentation for more information.
Upvotes: 1