Checking if an object is a number in C#

前端 未结 11 1566
粉色の甜心
粉色の甜心 2020-11-29 19:35

I\'d like to check if an object is a number so that .ToString() would result in a string containing digits and +,-,.

相关标签:
11条回答
  • 2020-11-29 20:14

    Taken from Scott Hanselman's Blog:

    public static bool IsNumeric(object expression)
    {
        if (expression == null)
        return false;
    
        double number;
        return Double.TryParse( Convert.ToString( expression
                                                , CultureInfo.InvariantCulture)
                              , System.Globalization.NumberStyles.Any
                              , NumberFormatInfo.InvariantInfo
                              , out number);
    }
    
    0 讨论(0)
  • 2020-11-29 20:22

    If your requirement is really

    .ToString() would result in a string containing digits and +,-,.

    and you want to use double.TryParse then you need to use the overload that takes a NumberStyles parameter, and make sure you are using the invariant culture.

    For example for a number which may have a leading sign, no leading or trailing whitespace, no thousands separator and a period decimal separator, use:

    NumberStyles style = 
       NumberStyles.AllowLeadingSign | 
       NumberStyles.AllowDecimalPoint | 
    double.TryParse(input, style, CultureInfo.InvariantCulture, out result);
    
    0 讨论(0)
  • 2020-11-29 20:24

    You could use code like this:

    if (n is IConvertible)
      return ((IConvertible) n).ToDouble(CultureInfo.CurrentCulture);
    else
      // Cannot be converted.
    

    If your object is an Int32, Single, Double etc. it will perform the conversion. Also, a string implements IConvertible but if the string isn't convertible to a double then a FormatException will be thrown.

    0 讨论(0)
  • 2020-11-29 20:27

    There are some great answers above. Here is an all-in-one solution. Three overloads for different circumstances.

    // Extension method, call for any object, eg "if (x.IsNumeric())..."
    public static bool IsNumeric(this object x) { return (x==null ? false : IsNumeric(x.GetType())); }
    
    // Method where you know the type of the object
    public static bool IsNumeric(Type type) { return IsNumeric(type, Type.GetTypeCode(type)); }
    
    // Method where you know the type and the type code of the object
    public static bool IsNumeric(Type type, TypeCode typeCode) { return (typeCode == TypeCode.Decimal || (type.IsPrimitive && typeCode != TypeCode.Object && typeCode != TypeCode.Boolean && typeCode != TypeCode.Char)); }
    
    0 讨论(0)
  • 2020-11-29 20:29

    There are three different concepts there:

    • to check if it is a number (i.e. a (typically boxed) numeric value itself), check the type with is - for example if(obj is int) {...}
    • to check if a string could be parsed as a number; use TryParse()
    • but if the object isn't a number or a string, but you suspect ToString() might give something that looks like a number, then call ToString() and treat it as a string

    In both the first two cases, you'll probably have to handle separately each numeric type you want to support (double/decimal/int) - each have different ranges and accuracy, for example.

    You could also look at regex for a quick rough check.

    0 讨论(0)
提交回复
热议问题