darking050
darking050

Reputation: 637

how to check if the character is an integer

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

Answers (10)

Babak Khodabandeh
Babak Khodabandeh

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

FredyWenger
FredyWenger

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

Lê Vũ Huy
Lê Vũ Huy

Reputation: 812

Simplest answer:

char chr = '1';
char.isDigit(chr)

Upvotes: -1

A.Clymer
A.Clymer

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

D Stanley
D Stanley

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

Corith Malin
Corith Malin

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

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

Try using System.Char.IsDigit method.

Upvotes: 2

Aamir
Aamir

Reputation: 5440

Try Char.IsNumber. Documentation and examples can be found here

Upvotes: 1

user586399
user586399

Reputation:

Use System.Char.IsDigit method

Upvotes: 43

lhan
lhan

Reputation: 4635

Integer.TryParse works well.

http://msdn.microsoft.com/en-us/library/f02979c7.aspx

Upvotes: 6

Related Questions