C# – input string is not in a correct format

ctype conversion

I want to calculate the percentage. But the compiler is giving an error that the input string is not in a correct format. Can some one elaborate what i am missing here?

private double per()
{
  double a = Convert.ToDouble(tbEnglish.Text+tbUrdu.Text+tbPhysics.Text+tbChemistry.Text+tbMaths.Text);
  double d = 500;
  double lblResult = (a / d)*100;
  return lblResult;
 }

Best Answer

You're concatenating the strings and then trying to convert that one result into a double. So for results of 75.6, 92.1, 56.3 78.2 and 72.3 you'd end up trying to parse "75.692.156.378.272.3".

Parse each value and then sum them.

However, I would strongly recommend that you use decimal for this instead of double. You should also consider using TryParse instead of Parse so that you can handle user input errors gracefully. Here's the solution sticking with Parse:

public decimal AveragePercentage()
{
    decimal sum = decimal.Parse(tbEnglish.Text) +
                  decimal.Parse(tbUrdu.Text) +
                  decimal.Parse(tbPhysics.Text) +
                  decimal.Parse(tbChemistry.Text) +
                  decimal.Parse(tbMaths.Text);
    return sum / 5m;
}

Out of interest, in your original code why are you dividing by 500 and then multiplying by 100? Why not just divide by 5 (as mine does now that I've noticed what was going on)?

As a side note, it's very important to differentiate between compile-time errors and execution-time errors. It wasn't the compiler saying that the input string wasn't in the correct format - it was the Convert.ToDouble method, at execution time. In this case it was relatively obvious, but in other situations we could have been chasing our tails for a while trying to find a compile-time problem when it was actually failing at execution time.