Exception 'The input string was not in an incorrect format' when doing calculation

1

I'm trying to do this calculation, using C #:

  

(x + 50) / 100) * 50 (x²-5x + 8))

I did it this way:

double Morte = ((int.Parse(TextBox1.Text) + 50) / 100) *50*(Math.Pow(int.Parse(TextBox1.Text),2)-5*int.Parse(TextBox1.Text)+8);

But every time I run the program and test it, it gives me this error:

  

System.FormatException: 'The input string was not in a correct format.'

    
asked by anonymous 20.11.2016 / 02:50

1 answer

1

It turns out that TextBox1.Text must have a value that can not be converted to number . Try to validate this, print it on the screen or in the console before trying to convert it to number.

My guess is that there is a blank at the beginning or the end.

To avoid this kind of thing, you can use a TryParse . The TryParse returns true if the conversion was successful and false otherwise.

See an example.

int valorDigitado;
bool conversaoSucedida = int.TryParse(TextBox1.Text, out valorDigitado);

if(!conversaoSucedida)
{
    MessageBox.Show("Valor digitado é inválido");
    return;
} 

double morte; // = cálculo;

It might also be interesting to use other approaches, some in conjunction with this one, but you can not give a lot of hint without having more details of what you intend to do. Already, it can be a good idea to use a TrimStart() and / or TrimEnd() to remove the spaces at the beginning and end of string . Depending on the context, you can use a regex and take only the numeric part of the string (I think a little exaggeration, but everything depends on context) or make a component that only accepts numbers as input ... Anyway, there are infinite possibilities .

About the error message

The error message in Portuguese is a bit of an idiot and the worst of it is that it has been this way since I know .NET.

The message:

  

The input string was not in an incorrect format

In fact, it should be

  

The input string was not in a correct format

The original message is:

  

Input string was not in a correct format

    
20.11.2016 / 03:44