What is the C# equivalent of NaN or IsNumeric?

后端 未结 15 998
心在旅途
心在旅途 2020-11-27 14:06

What is the most efficient way of testing an input string whether it contains a numeric value (or conversely Not A Number)? I guess I can use Double.Parse or a

15条回答
  •  时光取名叫无心
    2020-11-27 14:08

    I like the extension method, but don't like throwing exceptions if possible. I opted for an extension method taking the best of 2 answers here.

        /// 
        /// Extension method that works out if a string is numeric or not
        /// 
        /// string that may be a number
        /// true if numeric, false if not
        public static bool IsNumeric(this String str)
        {
            double myNum = 0;
            if (Double.TryParse(str, out myNum))
            {
                return true;
            }
            return false;
        }
    

提交回复
热议问题