Roger
Roger

Reputation: 69

"operator '+=' cannot be applied to operands of type 'decimal' and 'double' "

so i'm trying to write a method that looks at the selected items on a form and calculates the cost of a pizza. the variable is declare as type decimal but it is telling me i cannot use the += operator to add too the variable. however if i leave it as a decimal and just add whole numbers it allows it.

private decimal findTotal( )
    {
        decimal TotalDec = 0;

        //add size cost to total 
       if (sizeDDB .SelectedIndex == 0)
            TotalDec += 12;
        if (sizeDDB.SelectedIndex==1)  
            TotalDec += 14;
        if (sizeDDB.SelectedIndex == 2)
            TotalDec += 16;

        //add chrust cost
        if (crustDDB.SelectedIndex == 2)
            TotalDec += 2;

        // add topping cost
        if (sausageCB.Checked)
            TotalDec += 2;
        if (pepperoniCB.Checked)
            TotalDec += 1.5; //This is the line it doesn't like

        return TotalDec;
    }  

Upvotes: 1

Views: 4981

Answers (2)

Moshe D
Moshe D

Reputation: 778

This should work

TotalDec += 1.5m;

Upvotes: 11

Everyone
Everyone

Reputation: 1835

You need to cast

private decimal findTotal( )
{
    decimal TotalDec = 0;

    //add size cost to total 
   if (sizeDDB .SelectedIndex == 0)
        TotalDec += 12;
    if (sizeDDB.SelectedIndex==1)  
        TotalDec += 14;
    if (sizeDDB.SelectedIndex == 2)
        TotalDec += 16;

    //add chrust cost
    if (crustDDB.SelectedIndex == 2)
        TotalDec += 2;

    // add topping cost
    if (sausageCB.Checked)
        TotalDec += 2;
    if (pepperoniCB.Checked)
        TotalDec += (decimal)1.5; //there is no automatic casting from double to decimal, so you have to do it manually like this
    return TotalDec;
}

Upvotes: 1

Related Questions