Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

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?

like image 751
PramodChoudhari Avatar asked Feb 17 '11 08:02

PramodChoudhari


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

like image 123
Jonathan Wood Avatar answered Sep 30 '22 18:09

Jonathan Wood