0

In WinForm I need to check if the value in the TextBox is a number or not.

In PHP there is is_numeric function. Is something similar available in .NET?

user850010
  • 6,311
  • 12
  • 39
  • 60
  • @JustinNiessner - The OP is looking for a function similar to PHP's [`is_numeric`](http://php.net/manual/en/function.is-numeric.php). The linked answer does not provide some of the more advanced capabilities requested. – JDB Apr 29 '13 at 21:07
  • I'm satisfied with the link. No need to reopen. I just hope I'll be able to delete the question in two days:) – user850010 Apr 29 '13 at 21:17
  • 1
    I just felt annoyed by the fact that all the C# ninjas jumped into Int32.TryParse without checking what PHP is_numeric function covers.. – G.Y Apr 29 '13 at 21:21
  • As this question is closed, I've added my answer to the linked question. It actually answers the stated question: replicating `is_numeric`. See http://www.stackoverflow.com/a/16303109/211627 (Even if the OP is satisfied with the linked question/answer, replicating `is_numeric` is still an interesting challenge) – JDB Apr 30 '13 at 15:17
  • Thanks Cyborg37. I totally forgot about possible signs, digits in the numbers. upvoted your answer. – user850010 May 01 '13 at 16:55

4 Answers4

2

I'd use TryParse to check

string str = "123";
int i;

if (int.TryParse(str, out i))
{
    // it's an int
}

you should be able to do similar with other types, such as double

  • If you check the documentation for PHP's `is_numeric`, you'll find that `"0x4a"`, `"7.9"` and `"+1.2e3"` should also return `true`. – JDB Apr 29 '13 at 21:12
2

Int32.TryParse

int val;
bool parsed = Int32.TryParse(input_str, out val);

Gives you both if it's a valid int and the result of parsing it as int as well (in val)

J0HN
  • 26,063
  • 5
  • 54
  • 85
1
int number;
string str="!23";
if(int.TryParse(str, out number))
{
    //do something
}

if you are 100% sure its an int you can use:

int.Parse(str);

or

Convert.ToInt32(str);

it will cast an execption if its not an int

Kimtho6
  • 6,154
  • 9
  • 40
  • 56
0

double.tryparse will allow you to check the string.

rerun
  • 25,014
  • 6
  • 48
  • 78