如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
当前回答
int n;
bool isNumeric = int.TryParse("123", out n);
从c# 7开始更新:
var isNumeric = int.TryParse("123", out int n);
或者,如果不需要这个数字,可以丢弃out参数
var isNumeric = int.TryParse("123", out _);
变量可以被它们各自的类型替换!
其他回答
使用这些扩展方法可以清楚地区分检查字符串是数字还是字符串只包含0-9位数字
public static class ExtensionMethods
{
/// <summary>
/// Returns true if string could represent a valid number, including decimals and local culture symbols
/// </summary>
public static bool IsNumeric(this string s)
{
decimal d;
return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
}
/// <summary>
/// Returns true only if string is wholy comprised of numerical digits
/// </summary>
public static bool IsNumbersOnly(this string s)
{
if (s == null || s == string.Empty)
return false;
foreach (char c in s)
{
if (c < '0' || c > '9') // Avoid using .IsDigit or .IsNumeric as they will return true for other characters
return false;
}
return true;
}
}
在c# 7中,你可以内联out变量:
if(int.TryParse(str, out int v))
{
}
bool is_number(string str, char delimiter = '.')
{
if(str.Length==0) //Empty
{
return false;
}
bool is_delimetered = false;
foreach (char c in str)
{
if ((c < '0' || c > '9') && (c != delimiter)) //ASCII table check. Not a digit && not delimeter
{
return false;
}
if (c == delimiter)
{
if (is_delimetered) //more than 1 delimiter
{
return false;
}
else //first time delimiter
{
is_delimetered = true;
}
}
}
return true;
}
public static bool IsNumeric(this string input)
{
int n;
if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
{
foreach (var i in input)
{
if (!int.TryParse(i.ToString(), out n))
{
return false;
}
}
return true;
}
return false;
}
我已经使用了这个函数几次:
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;
}
但你也可以用;
bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false
从基准测试IsNumeric选项
(来源:aspalliance.com)
(来源:aspalliance.com)