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?

5
  • @JustinNiessner - The OP is looking for a function similar to PHP's is_numeric. The linked answer does not provide some of the more advanced capabilities requested. Commented Apr 29, 2013 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:) Commented Apr 29, 2013 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.. Commented Apr 29, 2013 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 stackoverflow.com/a/16303109/211627 (Even if the OP is satisfied with the linked question/answer, replicating is_numeric is still an interesting challenge) Commented Apr 30, 2013 at 15:17
  • Thanks Cyborg37. I totally forgot about possible signs, digits in the numbers. upvoted your answer. Commented May 1, 2013 at 16:55

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

If you check the documentation for PHP's is_numeric, you'll find that "0x4a", "7.9" and "+1.2e3" should also return true.
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)

Comments

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

Comments

0

double.tryparse will allow you to check the string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.