Identify if a string is a number
This will return true if input
is all numbers. Don't know if it's any better than TryParse
, but it will work.
Regex.IsMatch(input, @"^\d+$")
If you just want to know if it has one or more numbers mixed in with characters, leave off the ^
+
and $
.
Regex.IsMatch(input, @"\d")
Edit: Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.
You can also use:
using System.Linq;
stringTest.All(char.IsDigit);
It will return true
for all Numeric Digits (not float
) and false
if input string is any sort of alphanumeric.
Test case | Return value | Test result |
---|---|---|
"1234" |
true | ✅Pass |
"1" |
true | ✅Pass |
"0" |
true | ✅Pass |
"" |
true | ⚠️Fail (known edge case) |
"12.34" |
false | ✅Pass |
"+1234" |
false | ✅Pass |
"-13" |
false | ✅Pass |
"3E14" |
false | ✅Pass |
"0x10" |
false | ✅Pass |
Please note: stringTest
should not be an empty string as this would pass the test of being numeric.
I've used this function several times:
public static bool IsNumeric(object Expression)
{
double retNum;
bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
But you can also use;
bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false
From Benchmarking IsNumeric Options
(source: aspalliance.com)
(source: aspalliance.com)
int n;
bool isNumeric = int.TryParse("123", out n);
Update As of C# 7:
var isNumeric = int.TryParse("123", out int n);
or if you don't need the number you can discard the out parameter
var isNumeric = int.TryParse("123", out _);
The var s can be replaced by their respective types!