2

Say I've got a string which contains a number. I want to check if this number is an integer.

Examples

IsInteger("sss") => false 

IsInteger("123") => true

IsInterger("123.45") =>false
Community
  • 1
  • 1

3 Answers3

18

You can use int.TryParse. It will return a bool if it can parse the string and set your out parameter to the value

 int val;
if(int.TryParse(inputString, out val))
{
    //dosomething
}
mattlant
  • 15,384
  • 4
  • 34
  • 44
  • 1
    That answer above is only correct if the number will always be -2,147,483,648 to 2,147,483,647. If it is larger you will need long.TryParse(). EG: a 16 digit credit card number... – Ryan Sampson Mar 24 '09 at 22:04
5

There are two immediate options that you can use.

Option 1 - preferred - use Int32.TryParse.

int res;
Console.WriteLine(int.TryParse("sss", out res));
Console.WriteLine(int.TryParse("123", out res));
Console.WriteLine(int.TryParse("123.45", out res));
Console.WriteLine(int.TryParse("123a", out res));

This outputs:

False
True
False
False

Option 2 - use regular expressions

Regex pattern = new Regex("^-?[0-9]+$", RegexOptions.Singleline);
Console.WriteLine(pattern.Match("sss").Success);
Console.WriteLine(pattern.Match("123").Success);
Console.WriteLine(pattern.Match("123.45").Success);
Console.WriteLine(pattern.Match("123a").Success);

This outputs:

False
True
False
False
Jorge Ferreira
  • 96,051
  • 25
  • 122
  • 132
  • Hi, gave a vote for supplementing with regex. Its something i dont think of using enough in my daily work. Thanks. – mattlant Oct 11 '08 at 22:42
  • The examples are very useful. Especially to show that `int.TryParse` returns false for a decimal value. I was wondering if it might return true because the input value was numeric and truncate it to an integer. – Simon Elms Sep 11 '22 at 08:52
2

You can use System.Int32.TryParse and do something like this...

string str = "10";
int number = 0;
if (int.TryParse(str, out number))
{
    // True
}
else
{
    // False
}
Alex McBride
  • 6,881
  • 3
  • 29
  • 30