如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
当前回答
希望这能有所帮助
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)
这可能是c#中最好的选择。
如果你想知道字符串是否包含一个整数(整数):
string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);
TryParse方法将尝试将字符串转换为一个数字(整数),如果成功,它将返回true并将相应的数字放在myInt中。如果不能,则返回false。
使用其他响应中显示的int.Parse(someString)替代方法的解决方案是可行的,但它要慢得多,因为抛出异常的代价非常高。TryParse(…)在版本2中被添加到c#语言中,在此之前您没有选择。现在您做到了:因此应该避免使用Parse()替代方法。
如果你想接受十进制数,decimal类还有一个. tryparse(…)方法。在上面的讨论中,将int替换为decimal,同样的原则也适用。
下面是c#方法。 Int。TryParse方法(String, Int32)
Regex rx = new Regex(@"^([1-9]\d*(\.)\d*|0?(\.)\d*[1-9]\d*|[1-9]\d*)$");
string text = "12.0";
var result = rx.IsMatch(text);
Console.WriteLine(result);
检查字符串是否为uint, ulong或只包含数字1 .(点)和数字 样例输入
123 => True
123.1 => True
0.123 => True
.123 => True
0.2 => True
3452.434.43=> False
2342f43.34 => False
svasad.324 => False
3215.afa => False
在项目中导入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