Reputation: 637
I am looking for a function that can check the character if it is a integer and do something is so.
char a = '1';
if (Function(a))
{
do something
}
Upvotes: 32
Views: 68631
Reputation: 11
Parameters c Char The Unicode character to evaluate.
Returns Boolean true if c is a number; otherwise, false.
Examples The following example demonstrates IsNumber.
string str1 = "5";
string str2 = "non-numeric";
Console.WriteLine(Char.IsNumber(str1)); // Output: "True"
Console.WriteLine(Char.IsNumber(str, 3)); // Output: "False"
Upvotes: 1
Reputation: 2325
I have to check the first to characters of a string and if the third character is numeric and do it with MyString.All(char.IsDigit):
if (cAdresse.Trim().ToUpper().Substring(0, 2) == "FZ" & cAdresse.Trim().ToUpper().Substring(2, 1).All(char.IsDigit))
Upvotes: 0
Reputation: 492
The bool Char.IsDigit(char c);
Method should work perfectly for this instance.
char a = '1';
if (Char.IsDigit(a))
{
//do something
}
Upvotes: 6
Reputation: 152566
If you want just the pure 0-9
digits, use
if(a>='0' && a<='9')
IsNumeric
and IsDigit
both return true for some characters outside the 0-9 range:
Difference between Char.IsDigit() and Char.IsNumber() in C#
Upvotes: 25
Reputation: 1525
It may be better to just use a switch statement. Something like:
switch(a)
{
case '1':
//do something.
break;
case '2':
// do something else.
break;
default: // Not an integer
throw new FormatException();
break;
}
This will work as long as you're only looking for characters 0-9. Anything more than that (say "10") would be a string and not a character. If you're trying to just see if some input is an integer and the input is a string, you can do:
try
{
Convert.ToInt32("10")
}
catch (FormatException err)
{
// Not an integer, display some error.
}
Upvotes: 0
Reputation: 4635
Integer.TryParse
works well.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
Upvotes: 6