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:28

Another option - LINQ!

public static class StringExtensions
{
  public static bool IsDigits(this String text)
  {
    return !text.Any(c => !char.IsDigit(c));
  }
}

Note that this assumes you only want digits 0-9. If you want to accept decimal point, sign, exponent, etc, then repalce IsDigit() with IsNumber().

查看更多
叛逆
3楼-- · 2020-07-03 08:32

I've been using the following small code snippet for years as a pure C# IsNumeric function.

Granted, it's not exactly the same as the Microsoft.VisualBasic library's IsNumeric function as that (if you look at the decompiled code) involves lots of type checking and usage of the IConvertible interface, however this small function has worked well for me.

Note also that this function uses double.TryParse rather than int.TryParse to allow both integer numbers (including long's) as well as floating point numbers to be parsed. Also note that this function specifically asserts an InvariantCulture when parsing (for example) floating point numbers, so will correctly identify both 123.00 and 123,00 (note the comma and decimal point separators) as floating point numbers.

using System;
using System.Globalization;

namespace MyNumberFunctions
{
   public static class NumberFunctions
   {
      public static bool IsNumeric(this object expression)
      {
         if (expression == null)
         {
            return false;
         }
         double number;
         return Double.TryParse(Convert.ToString(expression, CultureInfo.InvariantCulture), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out number);
      }
   }
}

Usage is incredibly simple, since this is implemented as an extension method:

string myNumberToParse = "123.00";
bool isThisNumeric = myNumberToParse.IsNumeric();
查看更多
ゆ 、 Hurt°
4楼-- · 2020-07-03 08:34

You can still use the Visual Basic function in C#. The only thing you have to do is just follow my instructions shown below:

  1. Add the reference to the Visual Basic Library by right clicking on your project and selecting "Add Reference":

enter image description here

  1. Then import it in your class as shown below:

    using Microsoft.VisualBasic;

  2. Next use it wherever you want as shown below:

            if (!Information.IsNumeric(softwareVersion))
        {
            throw new DataException(string.Format("[{0}] is an invalid App Version!  Only numeric values are supported at this time.", softwareVersion));
        }
    

Hope, this helps and good luck!

查看更多
贼婆χ
5楼-- · 2020-07-03 08:36

Try this:

int temp;
return int.TryParse(input, out temp);

Of course, the behavior will be different from Visual Basic IsNumeric. If you want that behavior, you can add a reference to "Microsoft.VisualBasic" assembly and call the Microsoft.VisualBasic.Information.IsNumeric function directly.

查看更多
叛逆
6楼-- · 2020-07-03 08:37

If you use Int32.TryParse then you don't need to wrap the call in a TryCatch block, but otherwise, yes that is the approach to take.

查看更多
别忘想泡老子
7楼-- · 2020-07-03 08:37

Not exactly crazy about this approach, but you can just call the vb.net isNumeric function from C# by adding a reference to the Microsoft.VisualBasic.dll library...

bool x= Microsoft.VisualBasic.Information.IsNumeric("123");

The other approaches given are superior, but wanted to add this for the sake of completeness.

查看更多
登录 后发表回答