Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a string contains a numeric value

Tags:

string

c#

int

I am trying to check if a string contains a numeric value, if it doesnt return to a label if it does then I would like to show the main window. How can this be done?

If (mystring = a numeric value)
            //do this:
            var newWindow = new MainWindow();
            newWindow.Show();
If (mystring = non numeric)
            //display mystring in a label
            label1.Text = mystring;

else return error to message box
like image 314
Kirsty White Avatar asked Dec 13 '22 03:12

Kirsty White


2 Answers

use TryParse.

double val;
if (double.TryParse(mystring, out val)) {
    ..
} else { 
    ..
}

This will work for strings that translate directly to a number. If you need to worry about stuff like $ and , also, then you'll need to do a little more work to clean it up first.

like image 111
Jamie Treworgy Avatar answered Dec 25 '22 05:12

Jamie Treworgy


Int32 intValue;
if (Int32.TryParse(mystring, out intValue)){
  // mystring is an integer
}

Or, if it's a decimal number:

Double dblValue;
if (Double.TryParse(mystring, out dblValue)){
  // mystring has a decimal number
}

Some examples, BTW, can be found here.

Testing foo:
Testing 123:
    It's an integer! (123)
    It's a decimal! (123.00)
Testing 1.23:
    It's a decimal! (1.23)
Testing $1.23:
    It's a decimal! (1.23)
Testing 1,234:
    It's a decimal! (1234.00)
Testing 1,234.56:
    It's a decimal! (1234.56)

A couple more I've tested:

Testing $ 1,234:                      // Note that the space makes it fail
Testing $1,234:
    It's a decimal! (1234.00)
Testing $1,234.56:
    It's a decimal! (1234.56)
Testing -1,234:
    It's a decimal! (-1234.00)
Testing -123:
    It's an integer! (-123)
    It's a decimal! (-123.00)
Testing $-1,234:                     // negative currency also fails
Testing $-1,234.56:
like image 24
Brad Christie Avatar answered Dec 25 '22 07:12

Brad Christie