[c#] How can I check if a string is a number?

I'd like to know on C# how to check if a string is a number (and just a number).

Example :

141241   Yes
232a23   No
12412a   No

and so on...

Is there a specific function?

This question is related to c#

The answer is


Look up double.TryParse() if you're talking about numbers like 1, -2 and 3.14159. Some others are suggesting int.TryParse(), but that will fail on decimals.

string candidate = "3.14159";
if (double.TryParse(candidate, out var parsedNumber))
{
    // parsedNumber is a valid number!
}

EDIT: As Lukasz points out below, we should be mindful of the thread culture when parsing numbers with a decimal separator, i.e. do this to be safe:

double.TryParse(candidate, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var parsedNumber)


use this

 double num;
    string candidate = "1";
    if (double.TryParse(candidate, out num))
    {
        // It's a number!


 }

Starting with C# 7.0, you can declare the out variable in the argument list of the method call, rather than in a separate variable declaration. This produces more compact, readable code, and also prevents you from inadvertently assigning a value to the variable before the method call.

bool isDouble = double.TryParse(yourString, out double result);

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier


The problem with some of the suggested solutions is that they don't take into account various float number formats. The following function does it:

public bool IsNumber(String value)
{
    double d;
    if (string.IsNullOrWhiteSpace(value)) 
        return false; 
    else        
        return double.TryParse(value.Trim(), System.Globalization.NumberStyles.Any,
                            System.Globalization.CultureInfo.InvariantCulture, out d);
}

It assumes that the various float number styles such es decimal point (English) and decima comma (German) are all allowed. If that is not the case, change the number styles paramater. Note that Any does not include hex mumbers, because the type double does not support it.


public static void Main()
        {
            string id = "141241";
            string id1 = "232a23";
            string id2 = "12412a";

            validation( id,  id1,  id2);
        }

       public static void validation(params object[] list)
        {
            string s = "";
            int result;
            string _Msg = "";

            for (int i = 0; i < list.Length; i++)
            {
                s = (list[i].ToString());

               if (string.IsNullOrEmpty(s))
               {
                   _Msg = "Please Enter the value"; 
               }

               if (int.TryParse(s, out result))
               {
                   _Msg = "Enter  " + s.ToString() + ", value is Integer";

               }
               else
               {
                   _Msg = "This is not Integer value ";
               }
            }
        }

You should use the TryParse method for the int

string text1 = "x";
    int num1;
    bool res = int.TryParse(text1, out num1);
    if (res == false)
    {
        // String is not a number.
    }

Many datatypes have a TryParse-method that will return true if it managed to successfully convert to that specific type, with the parsed value as an out-parameter.

In your case these might be of interest:

http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx

http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx


string str = "123";
int i = Int.Parse(str);

If str is a valid integer string then it will be converted to integer and stored in i other wise Exception occur.


int value;
if (int.TryParse("your string", out value))
{
    Console.WriteLine(value);
}

Perhaps you're looking for the int.TryParse function.

http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx


You could use something like the following code:

    string numbers = "numbers you want to check";

    Regex regex = new Regex("^[0-9]+$"));

    if (regex.IsMatch(numbers))
    {
        //string value is a number
    }

int.TryPasrse() Methode is the best way so if the value was string you will never have an exception , instead of the TryParse Methode return to you bool value so you will know if the parse operation succeeded or failed

string yourText = "2";
int num;
bool res = int.TryParse(yourText, out num);
if (res == true)
{
    // the operation succeeded and you got the number in num parameter
}
else
{
   // the operation failed
}

Use int.TryParse():

string input = "141241";
int ouput;
bool result = int.TryParse(input, out output);

result will be true if it was.


I'm not a programmer of particularly high skills, but when I needed to solve this, I chose what is probably a very non-elegant solution, but it suits my needs.

    private bool IsValidNumber(string _checkString, string _checkType)
    {
        float _checkF;
        int _checkI;
        bool _result = false;

        switch (_checkType)
        {
            case "int":
                _result = int.TryParse(_checkString, out _checkI);
                break;
            case "float":
                _result = Single.TryParse(_checkString, out _checkF);
                break;
        }
        return _result;

    }

I simply call this with something like:

if (IsValidNumber("1.2", "float")) etc...

It means that I can get a simple true/false answer back during If... Then comparisons, and that was the important factor for me. If I need to check for other types, then I add a variable, and a case statement as required.


If you want to validate if each character is a digit and also return the character that is not a digit as part of the error message validation, then you can loop through each char.

string num = "123x";

foreach (char c in num.ToArray())
{
    if (!Char.IsDigit(c))
    {
        Console.WriteLine("character " + c + " is not a number");
        return;
    }
}

namespace Exception
{
    class Program
    {
        static void Main(string[] args)
        {
            bool isNumeric;
            int n;
            do
            {
                Console.Write("Enter a number:");
                isNumeric = int.TryParse(Console.ReadLine(), out n);
            } while (isNumeric == false);
            Console.WriteLine("Thanks for entering number" + n);
            Console.Read();
        }
    }
}

int num;
bool isNumeric = int.TryParse("123", out num);

This is my personal favorite

private static bool IsItOnlyNumbers(string searchString)
{
return !String.IsNullOrEmpty(searchString) && searchString.All(char.IsDigit);
}

Yep - you can use the Visual Basic one in C#.It's all .NET; the VB functions IsNumeric, IsDate, etc are actually static methods of the Information class. So here's your code:

using Microsoft.VisualBasic;
...
Information.IsNumeric( object );

int result = 0;
bool isValidInt = int.TryParse("1234", out result);
//isValidInt should be true
//result is the integer 1234

Of course, you can check against other number types, like decimal or double.


Try This

here i perform addition of no and concatenation of string

 private void button1_Click(object sender, EventArgs e)
        {
            bool chk,chk1;
            int chkq;
            chk = int.TryParse(textBox1.Text, out chkq);
            chk1 = int.TryParse(textBox2.Text, out chkq);
            if (chk1 && chk)
            {
                double a = Convert.ToDouble(textBox1.Text);
                double b = Convert.ToDouble(textBox2.Text);
                double c = a + b;
                textBox3.Text = Convert.ToString(c);
            }
            else
            {
                string f, d,s;
                f = textBox1.Text;
                d = textBox2.Text;
                s = f + d;
                textBox3.Text = s;
            }
        }

Regex.IsMatch(stringToBeChecked, @"^\d+$")

Regex.IsMatch("141241", @"^\d+$")  // True

Regex.IsMatch("232a23", @"^\d+$")  // False

Regex.IsMatch("12412a", @"^\d+$")  // False

Yes there is

int temp;
int.TryParse("141241", out temp) = true
int.TryParse("232a23", out temp) = false
int.TryParse("12412a", out temp) = false

Hope this helps.


If you just want to check if a string is all digits (without being within a particular number range) you can use:

string test = "123";
bool allDigits = test.All(char.IsDigit);

Use Int32.TryParse()

int num;

bool isNum = Int32.TryParse("[string to test]", out num);

if (isNum)
{
    //Is a Number
}
else
{
    //Not a number
}

MSDN Reference