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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With