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

<>

This question already has an answer here:

Answers


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.


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)

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


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

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

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

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

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.


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

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

    //}

Need Your Help

Should methods that are required to be executed in a specific order be private?

c#

I have a Class that retrieves some data and images does some stuff to them and them uploads them to a third party app using web services.