如果我有这些字符串:

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

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


当前回答

使用这些扩展方法可以清楚地区分检查字符串是数字还是字符串只包含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;
    }
}

其他回答

我已经使用了这个函数几次:

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# 7中,你可以内联out变量:

if(int.TryParse(str, out int v))
{
}

对于许多数据类型,您总是可以使用内置的TryParse方法来查看所讨论的字符串是否会通过。

的例子。

decimal myDec;
var Result = decimal.TryParse("123", out myDec);

结果将= True

decimal myDec;
var Result = decimal.TryParse("abc", out myDec);

结果将= False

//To my knowledge I did this in a simple way
static void Main(string[] args)
{
    string a, b;
    int f1, f2, x, y;
    Console.WriteLine("Enter two inputs");
    a = Convert.ToString(Console.ReadLine());
    b = Console.ReadLine();
    f1 = find(a);
    f2 = find(b);

    if (f1 == 0 && f2 == 0)
    {
        x = Convert.ToInt32(a);
        y = Convert.ToInt32(b);
        Console.WriteLine("Two inputs r number \n so that addition of these text box is= " + (x + y).ToString());
    }
    else
        Console.WriteLine("One or two inputs r string \n so that concatenation of these text box is = " + (a + b));
    Console.ReadKey();
}

static int find(string s)
{
    string s1 = "";
    int f;
    for (int i = 0; i < s.Length; i++)
       for (int j = 0; j <= 9; j++)
       {
           string c = j.ToString();
           if (c[0] == s[i])
           {
               s1 += c[0];
           }
       }

    if (s == s1)
        f = 0;
    else
        f = 1;

    return f;
}
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 _);

变量可以被它们各自的类型替换!