markzzz
markzzz

Reputation: 47945

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?

Upvotes: 31

Views: 151512

Answers (25)

James McCormack
James McCormack

Reputation: 9944

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)

Upvotes: 66

GinCanhViet
GinCanhViet

Reputation: 469

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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier

Upvotes: 1

Matt
Matt

Reputation: 27001

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.

Upvotes: 0

FreeBird
FreeBird

Reputation: 249

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

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

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

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

Upvotes: 0

bprathapoo
bprathapoo

Reputation: 141

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();
        }
    }
}

Upvotes: 0

Moath Titi
Moath Titi

Reputation: 1

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

Upvotes: 0

Admin File3
Admin File3

Reputation: 117

use this

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


 }

Upvotes: 0

AlexE
AlexE

Reputation: 41

This is my personal favorite

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

Upvotes: 4

user4618993
user4618993

Reputation:

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.

Upvotes: 0

Tanmay Nehete
Tanmay Nehete

Reputation: 2198

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;
            }
        }

Upvotes: 0

suneth
suneth

Reputation: 1

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 ";
               }
            }
        }

Upvotes: 0

Ash Burlaczenko
Ash Burlaczenko

Reputation: 25445

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.

Upvotes: 10

Waqar Janjua
Waqar Janjua

Reputation: 6123

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.

Upvotes: 1

Muhammad Al-Own
Muhammad Al-Own

Reputation: 237

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
}

Upvotes: 1

Carlos Quintanilla
Carlos Quintanilla

Reputation: 13303

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;
    }
}

Upvotes: 1

Joshua Honig
Joshua Honig

Reputation: 13215

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 );

Upvotes: 6

James Hill
James Hill

Reputation: 61802

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

Upvotes: 9

samy
samy

Reputation: 14962

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.
    }

Upvotes: 1

Theomax
Theomax

Reputation: 6792

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
    }

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160892

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);

Upvotes: 58

Andy_Vulhop
Andy_Vulhop

Reputation: 4789

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.

Upvotes: 1

Jackson Pope
Jackson Pope

Reputation: 14640

Use int.TryParse():

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

result will be true if it was.

Upvotes: 6

Jalal Said
Jalal Said

Reputation: 16162

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

Upvotes: 5

Dan Walker
Dan Walker

Reputation: 7163

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

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

Upvotes: 4

Andreas &#197;gren
Andreas &#197;gren

Reputation: 3929

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

Upvotes: 3

Related Questions