Lack of IsNumeric function in C#

2020-07-03 07:48发布

One thing that has bothered me about C# since its release was the lack of a generic IsNumeric function. I know it is difficult to generate a one-stop solution to detrmine if a value is numeric.

I have used the following solution in the past, but it is not the best practice because I am generating an exception to determine if the value is IsNumeric:

public bool IsNumeric(string input)
{
    try
    {
        int.Parse(input);
        return true;
    }
    catch
    {
        return false;
    }
}

Is this still the best way to approach this problem or is there a more efficient way to determine if a value is numeric in C#?

13条回答
虎瘦雄心在
2楼-- · 2020-07-03 08:41

You can use extension methods to extend the String type to include IsInteger:

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static bool IsInteger(this String input)
        {
             int temp;
             return int.TryParse(input, out temp);        
        }
    }   
}
查看更多
男人必须洒脱
3楼-- · 2020-07-03 08:43

Rather than using int.Parse, you can use int.TryParse and avoid the exception.

Something like this

public static bool IsNumeric(string input)
{
  int dummy;
  return int.TryParse(input, out dummy);
}

More generically you might want to look at double.TryParse.

One thing you should also consider is the potential of handling numeric string for different cultures. For example Greek (el-GR) uses , as a decimal separator while the UK (en-GB) uses a .. So the string "1,000" will either be 1000 or 1 depending on the current culture. Given this, you might consider providing overloads for IsNumeric that support passing the intended culture, number format etc. Take a look at the 2 overloads for double.TryParse.

查看更多
Ridiculous、
4楼-- · 2020-07-03 08:44
public bool IsNumeric(string input)
{
   int result;
   return Int32.TryParse(input,out result);
}
查看更多
乱世女痞
5楼-- · 2020-07-03 08:47

try this:

public static bool IsNumeric(object o)
{
    const NumberStyles sty = NumberStyles.Any;
    double d;
    return (o != null && Double.TryParse(o.ToString(), sty, null, out d));
}
查看更多
家丑人穷心不美
6楼-- · 2020-07-03 08:49

Take a look on the following answer: What is the C# equivalent of NaN or IsNumeric?

Double.TryParse takes care of all numeric values and not only ints.

查看更多
Animai°情兽
7楼-- · 2020-07-03 08:51

Lot's of TryParse answers. Here's something a bit different using Char.IsNumber():

    public bool IsNumeric(string s)
    {
        for (int i = 0; i < s.Length; i++)
        {
            if (char.IsNumber(s, i) == false)
            {
                return false;
            }
        }
        return true;
    }
查看更多
登录 后发表回答