If I have these strings:
\"abc\"
= false
\"123\"
= true
\"ab2\"
With c# 7 it you can inline the out variable:
if(int.TryParse(str, out int v))
{
}
Hope this helps
string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);
if isNumber
{
//string is number
}
else
{
//string is not a number
}
You can also use:
stringTest.All(char.IsDigit);
It will return true
for all Numeric Digits (not float
) and false
if input string is any sort of alphanumeric.
Please note: stringTest
should not be an empty string as this would pass the test of being numeric.
Try the reges below
new Regex(@"^\d{4}").IsMatch("6") // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg")
new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)
Here is the C# method. Int.TryParse Method (String, Int32)
In case you don't want to use int.Parse or double.Parse, you can roll your own with something like this:
public static class Extensions
{
public static bool IsNumeric(this string s)
{
foreach (char c in s)
{
if (!char.IsDigit(c) && c != '.')
{
return false;
}
}
return true;
}
}