How do I identify if a string is a number?

[Originally Posted By]: http://stackoverflow.com/questions/894263/how-do-i-identify-if-a-string-is-a-number

If I have these strings:

  1. "abc" = false
  2. "123" = true
  3. "ab2" = false

Is there a command, like IsNumeric or something else, that can identify if a string is a valid number?

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

This will return true if input is all numbers. Don’t know if it’s any better than TryParse, but it will work.

Regex.IsMatch(input, @"^\d+$")

If you just want to know if it has one or more numbers mixed in with characters, leave off the ^ +and $.

Regex.IsMatch(input, @"\d")

Edit: Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.

shareedit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s