如果我有这些字符串:

"abc" =假 "123" =真 "ab2" = false

是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?


当前回答

这可能是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,同样的原则也适用。

其他回答

在项目中导入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
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;
}

Kunal Noel回答的更新

stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.

但是,在这种情况下,我们有空字符串将通过测试,所以,你可以:

if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
   // Do your logic here
}

如果输入的都是数字,则返回true。不知道它是否比TryParse更好,但它会工作。

Regex.IsMatch(input, @"^\d+$")

如果您只想知道它是否有一个或多个数字与字符混合,请省略^ +和$。

Regex.IsMatch(input, @"\d")

编辑: 实际上,我认为它比TryParse更好,因为一个很长的字符串可能会溢出TryParse。

我知道这是一个老线程,但是没有一个答案真的对我有用——要么效率低,要么没有被封装以便于重用。我还想确保它在字符串为空或null时返回false。在这种情况下,TryParse返回true(当解析为数字时,空字符串不会导致错误)。这是我的字符串扩展方法:

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

使用简单:

var mystring = "1234.56789";
var test = mystring.IsNumeric();

或者,如果你想测试其他类型的数字,你可以指定“样式”。 所以,要用指数转换一个数字,你可以使用:

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

或者要测试一个潜在的十六进制字符串,你可以使用:

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

可选的'culture'参数也可以以大致相同的方式使用。

它的限制是不能转换太大而不能包含在double类型中的字符串,但这是一个有限的要求,我认为如果你处理的数字比这个大,那么你可能需要额外的专门的数字处理函数。