Nash Read
Nash Read

Reputation: 143

Converting Specific String/Integer into Decimal

I want the program to get all of the elem1-elem7 info, add it together, and put it into the totalElem variable. That part works fine.

The part I'm stuck on, is that I want to take that number (lets say 30 for example), and put it on the end of a decimal to use it as a multiplier. Therefore 30 would become 1.30.

The error I'm getting is:

Cannot implicitly convert type 'string' to 'decimal'.

Please note, that is not where the variable definitions really are in the code. I just put them there so I didn't have to post my whole program.

private void calculateButton_Click(object sender, EventArgs e)
{
    int startingSheetDPS;
    int chd;
    int skill;
    int elem7;
    int elem6;
    int elem5;
    int elem4;
    int elem3;
    int elem2;
    int elem1;
    int totalElem;
    decimal elemMultiplier;
    decimal baseMultiplier;

    elem1 = Convert.ToInt32(ele1.Text);
    elem2 = Convert.ToInt32(ele2.Text);
    elem3 = Convert.ToInt32(ele3.Text);
    elem4 = Convert.ToInt32(ele4.Text);
    elem5 = Convert.ToInt32(ele5.Text);
    elem6 = Convert.ToInt32(ele6.Text);
    elem7 = Convert.ToInt32(ele7.Text);
    chd = Convert.ToInt32(chd1.Text);
    skill = Convert.ToInt32(skill1.Text);

    totalElem = elem1 + elem2 + elem3 + elem4 + elem5 + elem6 + elem7;
    elemMultiplier = 1 + "." + totalElem;
}

In short, I want to be able to turn elemMultiplier into a decimal variable, containing 1.totalElem.

Upvotes: 2

Views: 80

Answers (3)

Grant Winney
Grant Winney

Reputation: 66439

Don't concatenate strings. Just do the math:

elemMultiplier =
  Convert.ToDecimal(1 + (totalElem / Math.Pow(10, totalElem.ToString().Length)));

(Edited after Gusman noticed a problem.)

Upvotes: 1

anik_s
anik_s

Reputation: 263

Use this:

String elemMul = "1." + totalElem.ToString();
elemMultiplier = Convert.ToDecimal(elemMul);

Your code shows problem because "." is a string which cannot be converted to decimal implicitly.

Upvotes: 2

Gusman
Gusman

Reputation: 15151

Ok, a really dirty and fast way, replace your

elemMultiplier = 1 + "." + totalElem;

with

elemMultiplier = decimal.Parse("1." + totalElem);

Be ware, this is locale-dependant.

Upvotes: 3

Related Questions