How do I identify if a string is a number?
If I have these strings:
"abc"
= false
"123"
= true
"ab2"
= false
Is there a command, like IsNumeric or something else, that can identify if a string is a valid number?
int n;
bool isNumeric = int.TryParse("123", out n);
Update As of C# 7:
var isNumeric = int.TryParse("123", out int n);
The var s can be replaced by their respective types!
This will return true if input
is all numbers. Don't know if it's any better than TryParse
, but it will work.
Regex.IsMatch(input, @"^d+$")
If you just want to know if it has one or more numbers mixed in with characters, leave off the ^
+
and $
.
Regex.IsMatch(input, @"d")
Edit: Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.
I've used this function several times:
public static bool IsNumeric(object Expression)
{
double retNum;
bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
But you can also use;
bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false
From Benchmarking IsNumeric Options
alt text http://aspalliance.com/images/articleimages/80/Figure1.gif
alt text http://aspalliance.com/images/articleimages/80/Figure2.gif
链接地址: http://www.djcxy.com/p/64110.html下一篇: 如何识别字符串是否是数字?