Reputation: 125
i have written this code i am getting an error at if(tot=100) Literal of double type cannot be implicitly converted to decimal
//value in textboxes
decimal p1 = Convert.ToDecimal(TextBox2.Text);
decimal p2 = Convert.ToDecimal(TextBox3.Text);
decimal p3 = Convert.ToDecimal(TextBox4.Text);
decimal p4 = Convert.ToDecimal(TextBox5.Text);
decimal p5 = Convert.ToDecimal(TextBox6.Text);
decimal p6 = Convert.ToDecimal(TextBox7.Text);
//adding all the p's
decimal tot = p1 + p2 + p3 + p4 + p5 + p6;
if (tot = 100.00)
{
Label2.Text = "Percentage is 100"
}
else
{
Label2.Text = "Total of percentages is not 100.";
}
Upvotes: 0
Views: 1089
Reputation: 21
The type of the literal should be made clear from the literal itself, and the type of variable it's assigned to should be assignable to from the type of that literal. There's no implicit conversion from double to decimal (as it can lose information).
Use an 'M' suffix to create a literal of this type like 100.00M.
Upvotes: 1
Reputation: 11675
To specify a decimal
literal with a decimal point, you have to use the decimal specifier M
:
if(tot == 100.00M)
Otherwise, the compiler assumes you want a double
(which is what the exception message is referring to - a double can't be converted to a decimal without an explicit cast).
However, in this example the .00
is redundant, so you could just use:
if(tot == 100M)
As mentioned in the other answers, you have to make sure you use ==
when comparing values in an if statement. If you had done that, you would have received a slightly different exception: "Operator '==' cannot be applied to operands of type 'decimal' and 'double'"
, which may have made things a little clearer.
Upvotes: 5
Reputation: 11964
You have error:
if(tot=100.00)
is assign 100.00 to tot, not compare them. But if you will write
if(tot == 100.00M)
all will work
Upvotes: 1