Identify if a string is a number

前端 未结 25 3052
無奈伤痛
無奈伤痛 2020-11-22 00:13

If I have these strings:

  1. \"abc\" = false

  2. \"123\" = true

  3. \"ab2\"

相关标签:
25条回答
  • 2020-11-22 00:16

    With c# 7 it you can inline the out variable:

    if(int.TryParse(str, out int v))
    {
    }
    
    0 讨论(0)
  • 2020-11-22 00:16

    Hope this helps

    string myString = "abc";
    double num;
    bool isNumber = double.TryParse(myString , out num);
    
    if isNumber 
    {
    //string is number
    }
    else
    {
    //string is not a number
    }
    
    0 讨论(0)
  • 2020-11-22 00:17

    You can also use:

    stringTest.All(char.IsDigit);
    

    It will return true for all Numeric Digits (not float) and false if input string is any sort of alphanumeric.

    Please note: stringTest should not be an empty string as this would pass the test of being numeric.

    0 讨论(0)
  • 2020-11-22 00:17

    Try the reges below

    new Regex(@"^\d{4}").IsMatch("6")    // false
    new Regex(@"^\d{4}").IsMatch("68ab") // false
    new Regex(@"^\d{4}").IsMatch("1111abcdefg")
    new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)
    
    0 讨论(0)
  • 2020-11-22 00:18

    Here is the C# method. Int.TryParse Method (String, Int32)

    0 讨论(0)
  • 2020-11-22 00:19

    In case you don't want to use int.Parse or double.Parse, you can roll your own with something like this:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题