Abid
Abid

Reputation: 133

input string is not in a correct format

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;
 }

Upvotes: 0

Views: 1708

Answers (2)

Dominic Barnes
Dominic Barnes

Reputation: 28439

I don't have Visual Studio available to me here on my Linux box, but I think you're better off with code like this.

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

In your example, you end up building a string that will look like: "75.692.156.372.3", which cannot be parsed into a double.

You need to convert all the TextBox.Text values into Decimals before using the + operator.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503859

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.

Upvotes: 4

Related Questions