2

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.

3 Answers 3

3

Ok, a really dirty and fast way, replace your

elemMultiplier = 1 + "." + totalElem;

with

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

Be ware, this is locale-dependant.

3
  • +1, exactly what I was going to say. You beat me to it by like 7 seconds :) Apr 13, 2014 at 23:31
  • If you want to make it locale-independant use CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator instead of dot.
    – Gusman
    Apr 13, 2014 at 23:31
  • Worked beautifully. Thanks.
    – Nash Read
    Apr 14, 2014 at 2:09
2

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.

1

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.)

1
  • That's completely wrong, if the sum is bigger than 100 will yield integers, that's not what he asked for.
    – Gusman
    Apr 13, 2014 at 23:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.