Identify if a string is a number

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

If I have these strings:

  1. \"abc\" = false

  2. \"123\" = true

  3. \"ab2\"

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

    If you want to catch a broader spectrum of numbers, à la PHP's is_numeric, you can use the following:

    // 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 );
    }
    

    Unit Test:

    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 );
    }
    

    Keep in mind that just because a value is numeric doesn't mean it can be converted to a numeric type. For example, "999999999999999999999999999999.9999999999" is a perfeclty valid numeric value, but it won't fit into a .NET numeric type (not one defined in the standard library, that is).

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

    If you want to check if a string is a number (I'm assuming it's a string since if it's a number, duh, you know it's one).

    • Without regex and
    • using Microsoft's code as much as possible

    you could also do:

    public static bool IsNumber(this string aNumber)
    {
         BigInteger temp_big_int;
         var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
         return is_number;
    }
    

    This will take care of the usual nasties:

    • Minus (-) or Plus (+) in the beginning
    • contains decimal character BigIntegers won't parse numbers with decimal points. (So: BigInteger.Parse("3.3") will throw an exception, and TryParse for the same will return false)
    • no funny non-digits
    • covers cases where the number is bigger than the usual use of Double.TryParse

    You'll have to add a reference to System.Numerics and have using System.Numerics; on top of your class (well, the second is a bonus I guess :)

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

    This will return true if input is all numbers. Don't know if it's any better than TryParse, but it will work.

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

    If you just want to know if it has one or more numbers mixed in with characters, leave off the ^ + and $.

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

    Edit: Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.

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

    I've used this function several times:

    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;
    }
    

    But you can also use;

    bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
    bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false
    

    From Benchmarking IsNumeric Options


    (source: aspalliance.com)


    (source: aspalliance.com)

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

    UPDATE of Kunal Noel Answer

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

    But, for this case we have that empty strings will pass that test, so, you can:

    if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
       // Do your logic here
    }
    
    0 讨论(0)
  • 2020-11-22 00:23

    The best flexible solution with .net built-in function called- char.IsDigit. It works with unlimited long numbers. It will only return true if each character is a numeric number. I used it lot of times with no issues and much easily cleaner solution I ever found. I made a example method.Its ready to use. In addition I added validation for null and empty input. So the method is now totally bulletproof

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