Identify if a string is a number

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

If I have these strings:

  1. \"abc\" = false

  2. \"123\" = true

  3. \"ab2\"

25条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 00:33

    Use these extension methods to clearly distinguish between a check if the string is numerical and if the string only contains 0-9 digits

    public static class ExtensionMethods
    {
        /// 
        /// Returns true if string could represent a valid number, including decimals and local culture symbols
        /// 
        public static bool IsNumeric(this string s)
        {
            decimal d;
            return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
        }
    
        /// 
        /// Returns true only if string is wholy comprised of numerical digits
        /// 
        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;
        }
    }
    

提交回复
热议问题