如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
当前回答
我已经使用了这个函数几次:
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)
其他回答
如果输入的都是数字,则返回true。不知道它是否比TryParse更好,但它会工作。
Regex.IsMatch(input, @"^\d+$")
如果您只想知道它是否有一个或多个数字与字符混合,请省略^ +和$。
Regex.IsMatch(input, @"\d")
编辑: 实际上,我认为它比TryParse更好,因为一个很长的字符串可能会溢出TryParse。
在项目中导入Visual Basic引用并使用其信息。IsNumeric方法,如下所示,并且能够捕获浮点数以及整数,不像上面的答案只捕获int。
// Using Microsoft.VisualBasic;
var txt = "ABCDEFG";
if (Information.IsNumeric(txt))
Console.WriteLine ("Numeric");
IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false
如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,你知道它是1)。
没有正则表达式和 尽可能多地使用微软的代码
你还可以:
public static bool IsNumber(this string aNumber)
{
BigInteger temp_big_int;
var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
return is_number;
}
这将解决通常的麻烦:
开头是负(-)或正(+ BigIntegers不会解析带小数点的数字。(因此:BigInteger.Parse("3.3")将抛出异常,而TryParse将返回false) 没有搞笑的非数字 适用于数字大于Double通常用法的情况。TryParse
您必须向System添加一个引用。数字和有 使用System.Numerics;名列全班第一(好吧,我猜第二名是额外奖励:)
希望这能有所帮助
string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);
if isNumber
{
//string is number
}
else
{
//string is not a number
}
我已经使用了这个函数几次:
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)