Int32 intValue;
if (Int32.TryParse(mystring, out intValue)){
// mystring is an integer
}
或者,如果它是十进制数:
Double dblValue;
if (Double.TryParse(mystring, out dblValue)){
// mystring has a decimal number
}
一些例子,顺便说一句,可以在这里找到。
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)
我测试过的还有几个:
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: