检查字符串是否包含数值

Kir*_*ite 4 c# string int

我试图检查字符串是否包含数字值,如果它没有返回标签,如果它然后我想显示主窗口.如何才能做到这一点?

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
Run Code Online (Sandbox Code Playgroud)

Jam*_*rgy 6

使用TryParse.

double val;
if (double.TryParse(mystring, out val)) {
    ..
} else { 
    ..
}
Run Code Online (Sandbox Code Playgroud)

这适用于直接转换为数字的字符串.如果你需要担心像$这样的东西,那么你还需要做一些工作来先清理它.


Bra*_*tie 5

Int32 intValue;
if (Int32.TryParse(mystring, out intValue)){
  // mystring is an integer
}
Run Code Online (Sandbox Code Playgroud)

或者,如果是十进制数:

Double dblValue;
if (Double.TryParse(mystring, out dblValue)){
  // mystring has a decimal number
}
Run Code Online (Sandbox Code Playgroud)

一些例子,BTW,可以在这里找到.

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)
Run Code Online (Sandbox Code Playgroud)

我测试了几个:

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:
Run Code Online (Sandbox Code Playgroud)