51

I know it's possible to check whether the value of a text box or variable is numeric using try/catch statements, but IsNumeric is so much simpler. One of my current projects requires recovering values from text boxes. Unfortunately, it is written in C#.

I understand that there's a way to enable the Visual Basic IsNumeric function in Visual C# by adding a reference to Visual Basic, though I don't know the syntax for it. What I need is a clear and concise walkthrough for enabling the IsNumeric function in C#. I don't plan on using any other functions indigenous to Visual Basic.

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
user3352070
  • 585
  • 1
  • 4
  • 9

12 Answers12

93
public bool IsNumeric(string value)
{
    return value.All(char.IsNumber);
}
CodeDog
  • 949
  • 6
  • 2
  • 3
    Best answer when one can't assume the numeric string will within allowable range of `[type]` when using `[type].TryParse(string, out [type])` – fiat Apr 19 '17 at 05:07
  • 18
    This answer is good, but the method should be called IsOnlyNumbers to be clear what it does. For instance, it will return false for decimal or currency values – userSteve Jul 03 '18 at 09:22
  • 1
    `public static bool IsNumeric(string value) => value.All(char.IsNumber);` – Jesse Hufstetler Feb 04 '19 at 21:54
  • 1
    `public static bool IsNumeric(this string value) => value.All(char.IsNumber);` – Jesse Hufstetler Feb 04 '19 at 21:55
  • it needs of "using System.Linq;" – usr4217 Mar 21 '19 at 12:00
  • 5
    Also note that this will evaluate to true for empty strings which TryParse will return false for. – DaeDaLuS_015 Mar 26 '19 at 15:19
  • While only good for unsigned integers it is short and can easily used without even a method.. – TaW Aug 10 '19 at 12:46
  • Just so everyone else knows, this will return false for 123.45 because of the dot. – Chris Rae Nov 03 '21 at 21:11
  • was using this and kept getting errors that wouldn't throw, and was causing performance issues (I'm using vscode on a mac, errors threw on my pc's). switched to this and works perfectly...why recreate the wheel https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.information.isnumeric?view=net-6.0 – Joe Shakely May 16 '22 at 00:31
50

To totally steal from Bill answer you can make an extension method and use some syntactic sugar to help you out.

Create a class file, StringExtensions.cs

Content:

public static class StringExt
{
    public static bool IsNumeric(this string text)
    {
        double test;
        return double.TryParse(text, out test);
    }
}

EDIT: This is for updated C# 7 syntax. Declaring out parameter in-line.

public static class StringExt
{
    public static bool IsNumeric(this string text) => double.TryParse(text, out _);
}

Call method like such:

var text = "I am not a number";
text.IsNumeric()  //<--- returns false
Cubicle.Jockey
  • 3,288
  • 1
  • 19
  • 31
  • 1
    Don't you need ( this string text ) in method declaration? – Derek Apr 02 '14 at 22:18
  • Yes you are correct. Thanks for noticing my typo. :) – Cubicle.Jockey Apr 03 '14 at 21:24
  • 2
    You can now replace "out double test" with "out _" (note 'double' is gone too). The underscore is a "fake" discard variable in C# 7. It can be used multiple times in the same scope since it isn't really a variable. It has no actual type. – Chris Bordeman Oct 17 '19 at 03:03
  • 1
    I like the idea. How about adding a check if the string contains null or whitespace to make it more robust, like `public static bool IsNumeric(this string text) => (string.IsNullOrWhiteSpace(text)) ? false : double.TryParse(text, out _);` ? – Matt Jan 19 '21 at 09:49
  • Null, Empty String and Whitespace will all already fail and return false from the TryParse. I love string.IsNullOrWhitespace but in this case it because of extra checking IMHO. – Cubicle.Jockey Jan 19 '21 at 21:17
25

You could make a helper method. Something like:

public bool IsNumeric(string input) {
    int test;
    return int.TryParse(input, out test);
}
Oscar
  • 13,594
  • 8
  • 47
  • 75
Bill
  • 1,431
  • 10
  • 13
  • private void btnOK_Click(object sender, EventArgs e) { if (startingbudget.IsNumeric()) { MessageBox.Show("This is a number."); } } – user3352070 Apr 02 '14 at 21:21
  • 4
    Now you can just type `return int.TryParse(input, out int test);` – Milad Jul 19 '17 at 12:21
  • 2
    For C# 7, the return can use the discard/ignore underscore without the int test. Like this: `return int.TryParse(input, out _);` – puddleglum Feb 23 '21 at 21:40
8

It is worth mentioning that one can check the characters in the string against Unicode categories - numbers, uppercase, lowercase, currencies and more. Here are two examples checking for numbers in a string using Linq:

var containsNumbers = s.Any(Char.IsNumber);
var isNumber = s.All(Char.IsNumber);

For clarity, the syntax above is a shorter version of:

var containsNumbers = s.Any(c=>Char.IsNumber(c));
var isNumber = s.All(c=>Char.IsNumber(c));

Link to unicode categories on MSDN:

UnicodeCategory Enumeration

pasx
  • 2,718
  • 1
  • 34
  • 26
  • 1
    A string that can be parsed as a numeric doesn't have to be made up of solely numeric characters. -1.2e-3 is numeric. It contains "-", "." and "e". You can't just add them to the list of acceptable characters. "0.0.0" is not a numeric string. – William Smith Nov 07 '22 at 13:35
6

Using C# 7 (.NET Framework 4.6.2) you can write an IsNumeric function as a one-liner:

public bool IsNumeric(string val) => int.TryParse(val, out int result);

Note that the function above will only work for integers (Int32). But you can implement corresponding functions for other numeric data types, like long, double, etc.

andersh
  • 8,105
  • 6
  • 39
  • 30
5

http://msdn.microsoft.com/en-us/library/wkze6zky.aspx

menu: Project-->Add Reference

click: assemblies, framework

Put a checkmark on Microsoft.VisualBasic.

Hit OK.

That link is for Visual Studio 2013, you can use the "Other versions" dropdown for different versions of visual studio.

In all cases you need to add a reference to the .NET assembly "Microsoft.VisualBasic".

At the top of your c# file you neeed:

using Microsoft.VisualBasic;

Then you can look at writing the code.

The code would be something like:

   private void btnOK_Click(object sender, EventArgs e)
   {
      if ( Information.IsNumeric(startingbudget) )
      {
         MessageBox.Show("This is a number.");
      }
   }
Derek
  • 7,615
  • 5
  • 33
  • 58
  • "Other versions" dropdown? Where? (VS 2012) – user3352070 Apr 02 '14 at 20:39
  • At the top of the webpage. The link for VS 2012 is also here: http://msdn.microsoft.com/en-us/library/wkze6zky(v=vs.110).aspx – Derek Apr 02 '14 at 20:41
  • It's not working. I've tried to use it the same way I would in VB, but it keeps coming out as an error. Are you sure this process works? – user3352070 Apr 02 '14 at 20:45
  • Did you manage to add the reference? What is your error message? What is the code you are using? You will be able to use this process to make it work. – Derek Apr 02 '14 at 21:17
  • private void btnOK_Click(object sender, EventArgs e) { if (startingbudget.IsNumeric()) { MessageBox.Show("This is a number."); } } – user3352070 Apr 02 '14 at 21:23
  • I have "using Microsoft.VisualBasic;" at the top of the program, too. For the record, I'm creating a Windows form. I get the same error even if I use StartingBudget.Text. – user3352070 Apr 02 '14 at 21:25
  • I updated the code you posted with how you need to use IsNumeric in c#. ( In my post above ) – Derek Apr 02 '14 at 21:45
  • 'decimal' does not containg a definition for 'IsNumeric'. It's a syntax error, and it's asking if I'm missing an assembly reference. I swear the using statement is at the top of my code. – user3352070 Apr 03 '14 at 00:13
  • Wait, that makes no sense! In VB, all I have to do is invoke the function. I've never seen the namespace 'Information' before. – user3352070 Apr 03 '14 at 00:16
  • In any case, thank you. The my program is working just fine, now. – user3352070 Apr 03 '14 at 00:16
  • Derek's method worked for me. I'm using .net 4.7.2. handle numeric, decimal and int . have not tested with scientific notation number but I don't need that for my app bool isNumeric(string input) { return Microsoft.VisualBasic.Information.IsNumeric(input); } – gg89 Mar 14 '19 at 20:57
3

Try following code snippet.

double myVal = 0;
String myVar = "Not Numeric Type";

if (Double.TryParse(myVar , out myNum)) {
  // it is a number
} else {
  // it is not a number
}
user353gre3
  • 2,747
  • 4
  • 24
  • 27
2

I usually handle things like this with an extension method. Here is one way implemented in a console app:

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            CheckIfNumeric("A");
            CheckIfNumeric("22");
            CheckIfNumeric("Potato");
            CheckIfNumeric("Q");
            CheckIfNumeric("A&^*^");

            Console.ReadLine();
        }

        private static void CheckIfNumeric(string input)
        {
            if (input.IsNumeric())
            {
                Console.WriteLine(input + " is numeric.");
            }
            else
            {
                Console.WriteLine(input + " is NOT numeric.");
            }
        }
    }

    public static class StringExtensions
    {
        public static bool IsNumeric(this string input)
        {
            return Regex.IsMatch(input, @"^\d+$");
        }
    }
}

Output:

A is NOT numeric.

22 is numeric.

Potato is NOT numeric.

Q is NOT numeric.

A&^*^ is NOT numeric.

Note, here are a few other ways to check for numbers using RegEx.

Community
  • 1
  • 1
Eric Scherrer
  • 3,328
  • 1
  • 19
  • 34
  • why not save code and just create a static method? public static bool IsNumeric(string input) { return Regex.IsMatch(input, @"^\d+$"); } – JJ_Coder4Hire Dec 17 '14 at 23:47
  • Like anything it depends. The assumption here is that the app will grow and StringExtensions class will also be added to, thus creating a centralized place for all this stuff. Not to mention the method above is indeed already static. – Eric Scherrer Dec 19 '14 at 15:18
0

Tested with Net6 and universal with object because needed in my app:

public static bool IsNumeric(this object text) => double.TryParse(Convert.ToString(text), out _);

Works with null and string.empty and also tested "".

mcpat
  • 1
  • 2
0
public static bool IsNumeric(string Value)
{
        return decimal.TryParse(Value, out _) || double.TryParse(Value, out _);
        /*
            decimal vs double:

            If a numeric value uses lot of decimal digits, it may not be convertible to 'double' type!
            If a numeric value is too big, it may not be convertible to 'decimal' type!

            Although in recent versions of Visual Studio Core, for number having too many decimal digits, 
            "double.TryParse(Value, out _)" returns "true" (which is not compatible with the conceptual 
            design of "double" type), it may not work in later versions of the compiler.

            Mr. "Jon Skeet" said some years ago:
            The range of a double value is much larger than the range of a decimal.
            0.1 is exactly representable in decimal but not in double, and decimal  
            actually uses a lot more bits for precision than double does.
        */
}
0

i read all suggested and compare its. this suggeste is better :

public static bool IsNumeric(string value) => double.TryParse(value, out _);

but this solusion is not perfect because is not support float number :

public bool static IsNumeric(string value)=>value.All(char.IsNumber);
BQF
  • 33
  • 7
-2

Is numeric can be achieved via many ways, but i use my way

public bool IsNumeric(string value)
{
    bool isNumeric = true;
    char[] digits = "0123456789".ToCharArray();
    char[] letters = value.ToCharArray();
    for (int k = 0; k < letters.Length; k++)
    {
        for (int i = 0; i < digits.Length; i++)
        {
            if (letters[k] != digits[i])
            {
                isNumeric = false;
                break;
            }
        }
    }
    return isNumeric;
}
cramopy
  • 3,459
  • 6
  • 28
  • 42
  • 1
    It may involve more lines of code than the Linq way, but it's clear what it does and probably just as quick if not quicker. Also doesn't rely on any framework outside of System – userSteve Jul 03 '18 at 09:19
  • Also, .IsNumeric and .IsDigit may return true for characters other than 0 to 9, see here https://stackoverflow.com/questions/228532/difference-between-char-isdigit-and-char-isnumber-in-c-sharp – userSteve Jul 03 '18 at 09:24
  • 1
    The for loop is not correct. Consider a test case where a number like "501" is passed to this method. If you follow the logic, it will be flagged as "isNumber == false" and exit because "5" != "0". – Luc Mar 21 '22 at 20:26