0

okay so I'm really confused about this problem and I don't know how to fix it. this is the code and I cant see what I did wrong:

        private void btnFormule_Click(object sender, EventArgs e)
        {

            double NumberA;
            NumberA = double.Parse(txtA.Text);

        }

it also does the same if I do convert.todouble(). But the weird thing is a while ago it didn't give an error when I did it like this so I don't know what's going on.

When I try it out it gives the error "System.FormatException: The format of the input string is incorrect" (its translated so it's not the exact error). if anyone has a solution to this problem it would really help

7
  • 1
    I suggest to use double.TryParse instead of double.Parse since not every string could be converted to a double, also you should take care about the current culture when parsing see here Commented Feb 7, 2020 at 11:14
  • As per the docs for double.Parse() you'll get a FormatException if the string you're passing does not represent a valid format Commented Feb 7, 2020 at 11:16
  • Check if it's a locale issue. Probably the decimal separator you're using is different from what the system expects. Use double.Parse(string s, IFormatProvider provider) Commented Feb 7, 2020 at 11:17
  • I like using Convert class and just wrap it into try/catch so function from it you need would be Convert.ToDouble(object) Commented Feb 7, 2020 at 11:18
  • @AleksaRistic Convert is nothing more than a wrapper for double.Parse. It fails exactly the same way if the format is wrong. It accepts a CultureInfo too. Commented Feb 7, 2020 at 11:29

1 Answer 1

1

You should use a combination of double.TryParse and CultureInfo

  private void btnFormule_Click(object sender, EventArgs e)
  {

      if(double.TryParse( textA.Text,NumberStyles.Any, CultureInfo.CurrentCulture, out double NumberA);
      {
        //Manage the valid parsing;
      }
      else
      {
        //Manage the not valid parsing
      }


    }
Sign up to request clarification or add additional context in comments.

2 Comments

CultureInfo.CurrentCulture is the default
you are right but here I don't know which is the problem with that string since the op didn't post it. I could suppose that the problem is on the decimal/thousand separator since this is different in many Culture. Of course he can set the culture to use instead of the current culture

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.