Exception 'Input character string was not in an incorrect format' when calculating

Asked

Viewed 1,477 times

1

I’m trying to do this calculation by 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 take the test, he gives me this mistake:

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

  • We need to know what is in the fields at the time you executed this code.

  • not that I was testing divide the account forgot to take xD.

  • when I type in the textbox a number 56 for example, it has q return me a value.any number I put it gives this exception.

1 answer

1

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

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

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

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

Perhaps it would also be interesting to use other approaches, some in conjunction with this, but there is no way to give much hint without having more details of what you intend to do. Already I say that it can be a good use TrimStart() and/or TrimEnd() to remove the spaces from the beginning and end of the string. Depending on the context, you can use a regex and take only the numerical part of the string (I think it’s a bit of an exaggeration, but it all depends on context) or making a component that only accepts numbers as input... Finally, there are infinite possibilities.


About the error message

The error message in Portuguese is kind of stupid and the worst is that it is like this since I know . NET.

The message:

The input character string was not in an incorrect format

In fact, it should be

The input character string was not in a format correct

The original message is:

Input string was not in a correct format

Browser other questions tagged

You are not signed in. Login or sign up in order to post.