5

How to check whether a given string in .NET is a number or not?

test1 - is string

1232 - is number

test - is string

tes3t - is string

2323k - is string

4567 - is number

How can I do this using system functions?

Mamta D
  • 6,310
  • 3
  • 27
  • 41
PramodChoudhari
  • 2,503
  • 12
  • 33
  • 46

10 Answers10

32

You can write a simple loop that tests each character.

bool IsNumber(string s)
{
    foreach (char c in s)
    {
        if (!Char.IsDigit(c))
            return false;
    }
    return s.Any();
}

Or you could use LINQ.

bool IsNumber(string s)
{
    return s.Any() && s.All(c => Char.IsDigit(c));
}

If you are more concerned about if the string can be represented as an int type than you are that all the characters are digits, you can use int.TryParse().

bool IsNumber(string s)
{
    int i;
    return int.TryParse(s, out i);
}

NOTE: You won't get much help if you don't start accepting some answers people give you.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • Why do you wanna check each character just to know if string has number or not ! – V4Vendetta Feb 17 '11 at 08:48
  • @V4Vendette If you look at the original question, the only cases he considered numbers were where *every* digits was a number. So how can you determine this without checking every digit? – Jonathan Wood Feb 17 '11 at 08:50
13

This will check if all chars are digits (will be true only for not negative integers)

inputString.All(c => IsDigit(c));

You can also try regular expression

string pattern = "^[-+]?[0-9]*\.?[0-9]*$";
Regex.IsMatch(inputString, pattern)
Itay Karo
  • 17,924
  • 4
  • 40
  • 58
4

Use int.TryParse(inputString, out outputInt) if ontputInt value is 0 (zero), then it is not a number.

Morten
  • 3,778
  • 2
  • 25
  • 45
  • 2
    Int32.TryParse returns a bool plus an out parameter with the parsed value (or default if it didn't work). Check the bool result to find out if it worked else "0" will be rejected. – Hans Kesting Feb 17 '11 at 08:51
1

Here we go:

public static class StringExtensions
    {
        public static bool IsDigits(this string input)
        {
            return input.All(c => !c.IsDigit());
        }

        public static bool IsDigit(this char input)
        {
            return (input < '0' || input > '9');
        }

    }

When called using the following, it should return true:

var justAString = "3131445";

var result = justAString.IsDigits();
Phil C
  • 3,687
  • 4
  • 29
  • 51
1

You can use Int32.TryParse or Int64.TryParse to try and convert string into a number.

Otherwise, you use following code as well:

public Boolean IsNumber(String s)
{
    foreach (Char ch in s)
    {
        if (!Char.IsDigit(ch)) return false;
    }
    return true;
}
decyclone
  • 30,394
  • 6
  • 63
  • 80
1

Use int.TryParse like this.

var test = "qwe";
int result;
if(int.TryParse(test, out result))
{
    //if test is int you can access it here in result;
}
naveen
  • 53,448
  • 46
  • 161
  • 251
1

The same using extention method for string. For this particular value "123.56" response will depend on the current culture.

    class Program
    {
        static void Main(string[] args)
        {
            string[] Values = {"123", "someword", "12yu", "123.56" };
            foreach(string val in Values)
                Console.WriteLine(string.Format("'{0}' - Is number?: {1}",val, val.IsNumber()));
        }
    }


    public static class StringExtension
    {        
        public static bool IsNumber(this String str)
        {
            double Number;
            if (double.TryParse(str, out Number)) return true;
            return false;            
        }
    }
apros
  • 2,848
  • 3
  • 27
  • 31
  • There is always a good case for int vs double parsing. Then you have to go down the line of independent culture specifics (which I have not done a great deal of in .NET but a lot of in Java) – Andez Jul 01 '13 at 10:26
0
//public static bool IsAlphaNumeric(string inputString)
    //{
    //    bool alpha = false;
    //    bool num = false;
    //    int  l;
    //    try
    //    {
    //       foreach (char s in inputString )
    //        {
    //            if (!char.IsDigit(s))
    //            {
    //                alpha = true;

    //            }
    //            else
    //            {
    //                num = true;
    //            }


    //        }
    //       if (num == true && alpha == true)
    //       {
    //           return true;
    //       }
    //       else
    //       {
    //           return false;
    //       }

    //    }
    //    catch
    //    {
    //        return false;
    //    }

    //}
GOVA
  • 1
0

If the length isn't specified, you have to resort to good old character by character comparison to determine if a character is digit or not.

If you expect it to be a integer with fixed number of bit, say a 32 bit integer,

then you can try something like Int32.TryParse.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
0

You can use

int parsed;
if( int.TryParse("is it a number?", out parsed) )

Here is a set of tests for the strings in original question. It uses an overload with ability to speify number style and culture.

    [Test]
    public void FalseOnStringyString()
    {
        var sources = new []{"test1", "test", "tes3t", "2323k"};

        foreach (var source in sources)
        {
            int parsed;
            Assert.IsFalse(int.TryParse(source, NumberStyles.Any, CultureInfo.InvariantCulture, out parsed));
        }
    }

    [Test]
    public void TrueOnNumberyString()
    {
        var sources = new[] { "1232", "4567" };

        foreach (var source in sources)
        {
            int parsed;
            Assert.IsTrue(int.TryParse(source, NumberStyles.Any, CultureInfo.InvariantCulture, out parsed));
        }
    }

Another solution would be using a Regex. But in this case the method does not output the number.

    [Test]
    public void TrueOnNumberyStringRegex()
    {
        var sources = new[] { "1232", "4567" };

        var isNumber = new Regex(@"^\d+$");

        foreach (var source in sources)
        {
            Assert.IsTrue(isNumber.IsMatch(source));
        }
    }

    [Test]
    public void FalseOnNumberyStringRegex()
    {
        var sources = new[] { "test1", "test", "tes3t", "2323k" };

        var isNumber = new Regex(@"^\d+$");

        foreach (var source in sources)
        {
            Assert.IsFalse(isNumber.IsMatch(source));
        }
    }
George Polevoy
  • 7,450
  • 3
  • 36
  • 61