Checking if an object is a number in C#

前端 未结 11 1574
粉色の甜心
粉色の甜心 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);
    }
    

提交回复
热议问题