31

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?

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • 1
    Depends what you mean by "number". A string containing only digits? An acceptably parseable int/long/float/double? Something else? – dlev Jul 18 '11 at 13:32
  • by number you mean integer or non negative integer or are decimal fractions allowed too? And what about scientific notation? – CodesInChaos Jul 18 '11 at 13:33
  • what about leading zero? i.e. "0123" is int or not? – Nika G. Jul 18 '11 at 13:42
  • 2
    What about `1.2` and `1,2` are both legal or illegal? What about `1e3`? What about `-2`? What about `88888888888888888888888888888888888888888888888888888888888888888888`? – Lasse V. Karlsen Jul 18 '11 at 14:22
  • 1.2 , 1,2 , -2, 88888888888888888888888888888888888888888888888888888888888888, all are number, so I need to return true :) – markzzz Jul 18 '11 at 14:30
  • possible duplicate of [How to check whether a string in .NET is a number or not?](http://stackoverflow.com/questions/5026689/how-to-check-whether-a-string-in-net-is-a-number-or-not). Also [how-to-identify-if-a-string-is-a-number?](http://stackoverflow.com/questions/894263/how-to-identify-if-a-string-is-a-number?lq=1) – nawfal Jan 18 '14 at 12:29
  • 3
    Possible duplicate of [How do I identify if a string is a number?](http://stackoverflow.com/questions/894263/how-do-i-identify-if-a-string-is-a-number) – AdrianHHH Feb 01 '17 at 11:59

25 Answers25

66

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)

James McCormack
  • 9,217
  • 3
  • 47
  • 57
  • 1
    please always use InvariantCulture while parsing strings – Lukasz Madon Jan 07 '12 at 01:55
  • That's interesting, is that to deal with commas signifying decimal point? – James McCormack Jan 09 '12 at 09:47
  • http://stackoverflow.com/questions/6428670/how-to-fix-an-application-that-has-a-problem-with-decimal-separator yep – Lukasz Madon Jan 09 '12 at 10:35
  • OK so I measured it to see what is the best pattern, Here are the results: test="1234" textAll(char.IsDigit) --> 00:00:00.0001493. Int32.TryParse(..) --> 00:00:00.0000012. We'd better use the TryParse pattern. – Jacob Apr 02 '17 at 00:44
  • 1
    It is now possible to do inline variable declarations so this works and is shorter with no need of seperate declaration of 'num': if (double.TryParse(candidate, out var num)) – Peter Jan 09 '18 at 12:33
58

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);
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • 3
    Amazing. I don't understand why this isn't higher. – eth0 Mar 20 '14 at 16:21
  • 1
    Just what i was looking for. Thanks. – NoonKnight Jul 30 '15 at 15:55
  • 3
    Just to note, if empty strings are unacceptable then this solution will fail with `"".All(Char.IsDigit)` (it returns `true`). You'll need to do `test.Any() && test.All(Char.IsDigit)` instead. – Pluto Nov 13 '15 at 23:00
  • 2
    using System.Linq; – alansiqueira27 Oct 21 '16 at 13:25
  • OK so I measured it to see what is the best pattern, Here are the results: test="1234" textAll(char.IsDigit) --> 00:00:00.0001493. Int32.TryParse(..) --> 00:00:00.0000012. We'd better use the TryParse pattern. – Jacob Apr 02 '17 at 00:43
10

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.

Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
9

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

James Hill
  • 60,353
  • 20
  • 145
  • 161
6

Use int.TryParse():

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

result will be true if it was.

Jackson Pope
  • 14,520
  • 6
  • 56
  • 80
6

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 );
Joshua Honig
  • 12,925
  • 8
  • 53
  • 75
  • 4
    Dude I just gave _C#_ code for using something in the VisualBasic _namespace_. Read the post and code! – Joshua Honig Jul 18 '11 at 13:43
  • `IsNumeric` is essentially a wrapper for `double.TryParse` – James McCormack Jul 18 '11 at 13:51
  • 1
    Interesting. However, IsNumeric is slightly more generous. This may or may not be what the poster is looking for, but it is worth noting. For examlple, `IsNumeric` will return true for a string with currency symbols (such as "$ 5,423.231"), but `double.TryParse` will return false for the same string. – Joshua Honig Jul 18 '11 at 14:21
5

This is my personal favorite

private static bool IsItOnlyNumbers(string searchString)
{
return !String.IsNullOrEmpty(searchString) && searchString.All(char.IsDigit);
}
AlexE
  • 51
  • 1
  • 1
5
int value;
if (int.TryParse("your string", out value))
{
    Console.WriteLine(value);
}
Jalal Said
  • 15,906
  • 7
  • 45
  • 68
4

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

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

Dan Walker
  • 7,123
  • 6
  • 30
  • 24
3

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

Andreas Ågren
  • 3,879
  • 24
  • 33
1

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

GinCanhViet
  • 353
  • 5
  • 13
1
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.

Andy_Vulhop
  • 4,699
  • 3
  • 25
  • 34
1

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.
    }
samy
  • 14,832
  • 2
  • 54
  • 82
1
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.

thkala
  • 84,049
  • 23
  • 157
  • 201
Waqar Janjua
  • 6,113
  • 2
  • 26
  • 36
1

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;
    }
}
Carlos Quintanilla
  • 12,937
  • 3
  • 22
  • 25
1

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
}
Muhammad Al-Own
  • 237
  • 3
  • 13
0
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 ";
               }
            }
        }
suneth
  • 1
0

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;
            }
        }
Tanmay Nehete
  • 2,138
  • 4
  • 31
  • 42
0

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.

0

use this

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


 }
Admin File3
  • 119
  • 10
0
int num;
bool isNumeric = int.TryParse("123", out num);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0
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();
        }
    }
}
Steve Drake
  • 1,968
  • 2
  • 19
  • 41
bprathapoo
  • 111
  • 1
  • 2
0
Regex.IsMatch(stringToBeChecked, @"^\d+$")

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

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

Regex.IsMatch("12412a", @"^\d+$")  // False
Floern
  • 33,559
  • 24
  • 104
  • 119
FreeBird
  • 230
  • 2
  • 4
0

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.

Matt
  • 25,467
  • 18
  • 120
  • 187
0

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
    }
Theomax
  • 6,584
  • 15
  • 52
  • 72