0

I am curious as to why this is giving me an error:

Input string was not in a correct format.

This error occurs because the screen is null so it should fail the check and not cause an exception.

if (double.Parse(textDisplay.Text) >= -2147483647 & textDisplay.Text != null)
1
  • What is the value of textDisplay.Text ? Commented Jul 9, 2013 at 6:18

5 Answers 5

5

First check if it is not null. Also use double && as single checks both arguments. Also you are better off with double.TryParse in case when input is in not numeric.

if (textDisplay.Text != null && double.Parse(textDisplay.Text) >= -2147483647)

Better version:

double value = 0;
if (double.TryParse(textDisplay.Text, out value) && value >= -2147483647)
Sign up to request clarification or add additional context in comments.

4 Comments

why checking if text is not null? TryParse makes it for you
removing first check make code a little bit more readable and result would be the same because TryParse works good with null values
@wudzik True, changed answer a bit
The reason I didn't use tryparse is because the only input it could possibly get was numerical, because it is a calculator. Thanks for the help!
1

Use TryParse instead of Parse and it won't raise exception and return boolean if it is valid

double res = 0;
if(double.TryParse("asd", out res))
{
   var a = res;
};

Comments

0

try && instead

if (double.Parse(textDisplay.Text) >= -2147483647 && textDisplay.Text != null)

or

double @num;

if(double.TryParse(textDisplay.Text, out @num) && @num >= -2147483647)
    return @num;

Comments

0
if (double.Parse(textDisplay.Text) >= -2147483647 & textDisplay.Text != null)

You should use double '&':

if (double.Parse(textDisplay.Text) >= -2147483647 && textDisplay.Text != null)

Comments

0

Use TryParse so It will not throw any error when TextBox value is empty or null

double displayValue = 0;
double.TryParse(textDisplay.Text, out displayValue)

if (displayValue >= -2147483647)

Comments

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.