0

I'm trying to Convert the string "5.7" (from a textbox) in to a float like this:

float m = float.Parse(TextBox9.Text);

But I'm getting the following error:

System.FormatException: Input string was not in a correct format.

what is wrong please?

Barry
  • 3,303
  • 7
  • 23
  • 42
Divyaanand Sinha
  • 366
  • 1
  • 3
  • 12

2 Answers2

1
float.Parse(Textbox9.Text, CultureInfo.InvariantCulture.NumberFormat);
user3378165
  • 6,546
  • 17
  • 62
  • 101
0

You et the exception, because the text in the TextBox9 does not fit the "country-rules" for a correct decimal number. Usually this happens, if the dot represents a thousand seperator and not the decimal point. Maybe you can use:

float number = float.Parse(TextBox9.Text, CultureInfo.InvariantCulture);

or

float number = float.Parse(TextBox9.Text, Thread.CurrentThread.CurrentUICulture);

To avoid the exception you can use:

float number;
if (!float.TryParse(TextBox9.Text,  out number))
    MessageBox.Show("Input must be a decimal number.");
scher
  • 1,813
  • 2
  • 18
  • 39
  • `Thread.CurrentThread.CurrentUICulture` used by default. Avoiding exception not very good approach – Fabio Jun 15 '16 at 05:26
  • Exceptions is very important to get information something goes wrong. On the top layer of application you can handle Exception and show some information about it to the user. When you avoiding exception, then you didn't get information about error – Fabio Jun 15 '16 at 06:05
  • I agrree with you in a multi layer design if e.g the input is checked in some model. But here we are in the top layer. Otherwise there would be no access to `TextBox9`. Additionally the requirement is to input a number. In this case for me the input of a non-number into the textbox is not an exceptional behaviour. Thats why I would avoid the exception. – scher Jun 15 '16 at 06:18
  • Input validation and sanitation **is entirely the right thing to do**. A program **should never crash due to *expected* values**, and *expected* here means "we know this will happen". The OP has to decide if his program should accept both `6.7` and `6,7` as the same thing or if they mean different things, and if it should mean different things in cultures that uses different decimal points and thousand separators. Since the OP seems to be clueless to these nuances, making him aware of this is **also the right thing to do**. – Lasse V. Karlsen Jun 15 '16 at 07:41