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
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With