How to check if a number is an integer in .NET?

北战南征 提交于 2020-06-28 03:59:09

问题


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

回答1:


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
}



回答2:


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



回答3:


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
}


来源:https://stackoverflow.com/questions/194089/how-to-check-if-a-number-is-an-integer-in-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!