首页 文章

如何识别字符串是否为数字?

提问于
浏览
597

如果我有这些字符串:

  • "abc" = false

  • "123" = true

  • "ab2" = false

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

23 回答

  • 9

    希望这可以帮助

    string myString = "abc";
    double num;
    bool isNumber = double.TryParse(myString , out num);
    
    if isNumber 
    {
    //string is number
    }
    else
    {
    //string is not a number
    }
    
  • -6

    对于许多数据类型,您始终可以使用内置的TryParse方法来查看相关字符串是否会通过 .

    例 .

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

    然后结果= True

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

    结果将= False

  • 5

    使用c#7,您可以内联out变量:

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

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

    如果您想知道字符串是否为数字,您可以尝试解析它:

    var numberString = "123";
    int number;
    
    int.TryParse(numberString , out number);
    

    请注意 TryParse 返回 bool ,您可以使用它来检查解析是否成功 .

  • 2

    这可能是C#中最好的选择 .

    如果您想知道字符串是否包含整数(整数):

    string someString;
    // ...
    int myInt;
    bool isNumerical = int.TryParse(someString, out myInt);
    

    TryParse方法将尝试将字符串转换为数字(整数),如果成功,它将返回true并将相应的数字放在myInt中 . 如果不能,则返回false .

    使用其他响应中显示的 int.Parse(someString) 替代方案的解决方案可行,但速度要慢得多,因为抛出异常非常昂贵 . TryParse(...) 已添加到版本2中的C#语言,在此之前您没有选择 . 现在你做了:因此你应该避免使用 Parse() 替代方案 .

    如果要接受十进制数,则十进制类也具有 .TryParse(...) 方法 . 在上面的讨论中用int替换int,并且适用相同的原则 .

  • 24

    您还可以使用:

    stringTest.All(char.IsDigit);
    

    如果输入字符串是任何类型的字母数字,它将为所有数字数字(不是 float )和 false 返回 true .

    Please notestringTest 不应该是空字符串,因为这会通过数字测试 .

  • 7

    如果您不想使用int.Parse或double.Parse,您可以使用以下内容滚动自己:

    public static class Extensions
    {
        public static bool IsNumeric(this string s)
        {
            foreach (char c in s)
            {
                if (!char.IsDigit(c) && c != '.')
                {
                    return false;
                }
            }
    
            return true;
        }
    }
    
  • 19

    在项目中引入对Visual Basic的引用,并使用其Information.IsNumeric方法,如下所示,并且能够捕获浮点数和整数,这与上面仅捕获整数的答案不同 .

    // Using Microsoft.VisualBasic;
    
        var txt = "ABCDEFG";
    
        if (Information.IsNumeric(txt))
            Console.WriteLine ("Numeric");
    
    IsNumeric("12.3"); // true
    IsNumeric("1"); // true
    IsNumeric("abc"); // false
    
  • 2

    Double.TryParse

    bool Double.TryParse(string s, out double result)
    
  • 930

    UPDATE of Kunal Noel Answer

    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
    }
    
  • 11
    //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;
    }
    
  • 0

    我想这个答案只会在所有其他答案之间丢失,但无论如何,这里也是如此 .

    我最终通过谷歌来回答这个问题,因为我想检查 string 是否为 numeric ,以便我可以使用 double.Parse("123") 而不是 TryParse() 方法 .

    为什么?因为如果解析失败,必须声明一个 out 变量并检查 TryParse() 的结果是很烦人的 . 我想使用 ternary operator 检查 string 是否 numerical 然后只是在第一个三元表达式中解析它或在第二个三元表达式中提供默认值 .

    像这样:

    var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;
    

    它比以下更清洁:

    var doubleValue = 0;
    if (double.TryParse(numberAsString, out doubleValue)) {
        //whatever you want to do with doubleValue
    }
    

    I made a couple extension methods for these cases:


    扩展方法一

    public static bool IsParseableAs<TInput>(this string value) {
        var type = typeof(TInput);
    
        var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
            new[] { typeof(string), type.MakeByRefType() }, null);
        if (tryParseMethod == null) return false;
    
        var arguments = new[] { value, Activator.CreateInstance(type) };
        return (bool) tryParseMethod.Invoke(null, arguments);
    }
    

    Example:

    "123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;
    

    因为 IsParseableAs() 尝试将字符串解析为适当的类型而不是仅仅检查字符串是否为"numeric"它应该是非常安全的 . 您甚至可以将它用于具有 TryParse() 方法的非数字类型,例如 DateTime .

    该方法使用反射,你最终调用 TryParse() 方法两次,当然效率不高,但不是所有东西都必须完全优化,有时方便更重要 .

    此方法还可用于轻松地将数字字符串列表解析为 double 列表或具有默认值的其他类型,而不必捕获任何异常:

    var sNumbers = new[] {"10", "20", "30"};
    var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);
    

    扩展方法二

    public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
        var type = typeof(TOutput);
    
        var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
            new[] { typeof(string), type.MakeByRefType() }, null);
        if (tryParseMethod == null) return defaultValue;
    
        var arguments = new object[] { value, null };
        return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
    }
    

    此扩展方法允许您将 string 解析为具有 TryParse() 方法的任何 type ,并且还允许您指定在转换失败时返回的默认值 .

    这比使用三元运算符和上面的扩展方法更好,因为它只进行一次转换,但仍使用反射...

    Examples:

    "123".ParseAs<int>(10);
    "abc".ParseAs<int>(25);
    "123,78".ParseAs<double>(10);
    "abc".ParseAs<double>(107.4);
    "2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
    "monday".ParseAs<DateTime>(DateTime.MinValue);
    

    Outputs:

    123
    25
    123,78
    107,4
    28.10.2014 00:00:00
    01.01.0001 00:00:00
    
  • 8

    具有.net内置功能的最佳灵活解决方案称为 char.IsDigit . 它适用于无限长号码 . 如果每个字符都是数字,它只会返回true . 我曾多次使用它,没有任何问题,而且我发现的解决方案更加轻松 . 我做了一个示例方法 . 它准备好了 . 另外,我添加了null和空输入的验证 . 所以这个方法现在完全是防弹的

    public static bool IsNumeric(string strNumber)
        {
            if (string.IsNullOrEmpty(strNumber))
            {
                return false;
            }
            else
            {
                int numberOfChar = strNumber.Count();
                if (numberOfChar > 0)
                {
                    bool r = strNumber.All(char.IsDigit);
                    return r;
                }
                else
                {
                    return false;
                }
            }
        }
    
  • 138

    您可以使用TryParse来确定字符串是否可以解析为整数 .

    int i;
    bool bNum = int.TryParse(str, out i);
    

    布尔值会告诉你它是否有效 .

  • 325
  • 6
    int n;
    bool isNumeric = int.TryParse("123", out n);
    

    Update 从C#7开始:

    var isNumeric = int.TryParse("123", out int n);
    

    var可以用它们各自的类型代替!

  • 1

    我知道这是一个旧线程,但没有一个答案真的为我做了 - 要么低效,要么没有封装以便于重用 . 我还想确保如果字符串为空或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();
    

    或者,如果要测试其他类型的数字,可以指定“样式” . 因此,要使用Exponent转换数字,您可以使用:

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

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

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

    可选的'culture'参数可以以相同的方式使用 .

    它受限于无法转换太大而不能包含在double中的字符串,但这是一个有限的要求,我认为如果您使用的数字大于此值,那么您可能需要额外的专门数字处理无论如何功能 .

  • 2

    如果 input 是所有数字,则返回true . 唐't know if it' s比 TryParse 好,但它会起作用 .

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

    如果您只想知道它是否有一个或多个数字与字符混合,请不要使用 ^ +$ .

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

    Edit: 实际上我认为它比TryParse更好,因为很长的字符串可能会溢出TryParse .

  • 112

    我已多次使用此功能:

    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
    

    Benchmarking IsNumeric Options

    alt text http://aspalliance.com/images/articleimages/80/Figure1.gif

    alt text http://aspalliance.com/images/articleimages/80/Figure2.gif

  • 0

    如果您想要捕获更广泛的数字,例如PHP的is_numeric,您可以使用以下内容:

    // From PHP documentation for is_numeric
    // (http://php.net/manual/en/function.is-numeric.php)
    
    // Finds whether the given variable is numeric.
    
    // Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
    // exponential part. Thus +0123.45e6 is a valid numeric value.
    
    // Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
    // only without sign, decimal and exponential part.
    static readonly Regex _isNumericRegex =
        new Regex(  "^(" +
                    /*Hex*/ @"0x[0-9a-f]+"  + "|" +
                    /*Bin*/ @"0b[01]+"      + "|" + 
                    /*Oct*/ @"0[0-7]*"      + "|" +
                    /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" + 
                    ")$" );
    static bool IsNumeric( string value )
    {
        return _isNumericRegex.IsMatch( value );
    }
    

    单元测试:

    static void IsNumericTest()
    {
        string[] l_unitTests = new string[] { 
            "123",      /* TRUE */
            "abc",      /* FALSE */
            "12.3",     /* TRUE */
            "+12.3",    /* TRUE */
            "-12.3",    /* TRUE */
            "1.23e2",   /* TRUE */
            "-1e23",    /* TRUE */
            "1.2ef",    /* FALSE */
            "0x0",      /* TRUE */
            "0xfff",    /* TRUE */
            "0xf1f",    /* TRUE */
            "0xf1g",    /* FALSE */
            "0123",     /* TRUE */
            "0999",     /* FALSE (not octal) */
            "+0999",    /* TRUE (forced decimal) */
            "0b0101",   /* TRUE */
            "0b0102"    /* FALSE */
        };
    
        foreach ( string l_unitTest in l_unitTests )
            Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );
    
        Console.ReadKey( true );
    }
    

    请记住,仅仅因为值是数字并不意味着它可以转换为数字类型 . 例如, "999999999999999999999999999999.9999999999" 是一个perfeclty有效数值,但它不适合.NET数字类型(不是标准库中定义的那个) .

  • 14
    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;
    }
    
  • 0

    如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,呃,你知道它是一个) .

    • 没有正则表达式和

    • 尽可能使用Microsoft的代码

    你也可以这样做:

    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.Numerics 的引用并且在你的 class 之上有 using System.Numerics; (好吧,第二个是我想的奖金:)

相关问题