Convert string to int and test success in C#

2019-01-14 05:19发布

How can you check whether a string is convertible to an int?

Let's say we have data like "House", "50", "Dog", "45.99", I want to know whether I should just use the string or use the parsed int value instead.

In JavaScript we had this parseInt() function. If the string couldn't be parsed, it would get back NaN.

4条回答
Summer. ? 凉城
2楼-- · 2019-01-14 06:11

Int32.TryParse(String, Int32) - http://msdn.microsoft.com/en-us/library/f02979c7.aspx

  bool result = Int32.TryParse(value, out number);
  if (result)
  {
     Console.WriteLine("Converted '{0}' to {1}.", value, number);         
  }
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-14 06:12

Int.TryParse

查看更多
唯我独甜
4楼-- · 2019-01-14 06:12

found this in one of the search results: How do I identify if a string is a number?

Adding this because the answers i saw before did not have usage:

int n;
bool isNumeric = int.TryParse("123", out n);

here "123" can be something like string s = "123" that the OP is testing and the value n will have a value (123) after the call if it is found to be numeric.

查看更多
相关推荐>>
5楼-- · 2019-01-14 06:20

Could you not make it a little more elegant by running the tryparse right into the if?

Like so:

if (Int32.TryParse(value, out number))     
  Console.WriteLine("Converted '{0}' to {1}.", value, number);
查看更多
登录 后发表回答