hi
if I have this strings:
"abc" = false
"123" = true
"ab2" = false
Is there any command like IsNumeric or something else that can identify if string has numbers?
thank's in advance
hi
if I have this strings:
"abc" = false
"123" = true
"ab2" = false
Is there any command like IsNumeric or something else that can identify if string has numbers?
thank's in advance
You can always use the built in TryParse methods for many datatypes to see if the string in question will pass.
Example.
Result = decimal.tryparse("123", myDec)
Result would then = True
Result = decimal.tryparse("abc", mydec)
Result would then = False
You can use TryParse to determine if the string can be parsed into an integer.
int i;
bool bNum = int.TryParse(str, out i);
The boolean will tell you if it worked or not.
If you want to know if a string is a number, you could always try parsing it:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
Note that TryParse
returns a bool
, which you can use to check if your parsing succeeded.
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;
}
}
This is probably the best option in C#.
If you want to know if the string contains a whole number (integer):
string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);
The TryParse method will try to convert the string to a number (integer) and if it succeeds it will return true and place the corresponding number in myInt. If it can't, it returns false.
Solutions using the int.Parse(somString)
alternative shown in other responses works, but it is much slower because throwing exceptions is very expensive. TryParse(...)
was added to the C# language in version 2, and until then you didn't have a choice. Now you do: you should avoid the Parse()
alternative.
If you want to accept decimal numbers, the decimal class also has a .TryParse(...)
method. Replace int with decimal in the above discussion, and the same principles apply.
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.