views:

4795

answers:

11

hi

if I have this strings:

  1. "abc" = false

  2. "123" = true

  3. "ab2" = false

Is there any command like IsNumeric or something else that can identify if string has numbers?

thank's in advance

+29  A: 
int n;
bool isNumeric = int.TryParse("123", out n);
mquander
Though, I would use double.TryParse, since we want to know if it represents a number at all.
John Gietzen
Cool !! thank's !!!
Gold
One caveat: TryParse could overflow if you have a very long string. If that's a possibility, regular expressions might be a better option (see my answer for an example).
John M Gant
If you know your string is a bit too long for int, use Int64.TryParse.
Sam
+4  A: 

You can always use the built in TryParse methods for many datatypes to see if the string in question will pass.

Example.

Result = decimal.tryparse("123", myDec)

Result would then = True

Result = decimal.tryparse("abc", mydec)

Result would then = False

TheTXI
I think I may have done that more in VB style syntax than C#, but the same rules apply.
TheTXI
+2  A: 

You can use TryParse to determine if the string can be parsed into an integer.

int i;
bool bNum = int.TryParse(str, out i);

The boolean will tell you if it worked or not.

Craig
+2  A: 

If you want to know if a string is a number, you could always try parsing it:

var numberString = "123";
int number;

int.TryParse(numberString , out number);

Note that TryParse returns a bool, which you can use to check if your parsing succeeded.

Gabriel Florit
+1  A: 

bool Double.TryParse( string s, out double result )

John Pirie
+2  A: 
if (Regex.Match("ab1", @".*([\d]+).*"))
{}
marduk
This is the only comment I saw that answered if a string CONTAINS numbers.
Chad Ruppert
You want IsMatch() which return bool, not Match(). Also your regex would return true for your example "ab1" and their example #3 "ab2", which is not what they want.
Lucas
@Lucas - ahh, you're absolutely right. It's ".IsMatch". And yea, I guess he wants to return "true" only if it's a pure number and not mixed content. It wouldn't be that hard to adjust the regex for that, but out of curiousity, does anyone have performance insights on using regex vs int32.parse?
marduk
+3  A: 

In case you don't want to use int.Parse or double.Parse, you can roll your own with something like this:

public static class Extensions
{
    public static bool IsNumeric(this string s)
    {
        foreach (char c in s)
        {
            if (!char.IsDigit(c) && c != '.')
            {
                return false;
            }
        }

        return true;
    }
}
BFree
you might as well return s.All(c => c.IsDigit(c) || c == '.'), but...
Lucas
What if they meant integers only? What about locales where '.' is the group separator, not the comma (e.g. pt-Br)? what about negative numbers? group separators (commas in English)? currency symbols? TryParse() can manage all of these as required using NumberStyles and IFormatProvider.
Lucas
Ooh yeah, I like the All version better. I've never actually used that extension method, good call. Although it should be s.ToCharArray().All(..). As for your second point, I hear ya, which is why I prefaced with if you don't want to use int.Parse.... (which I'm assuming has more overhead...)
BFree
+3  A: 

This is probably the best option in C#.

If you want to know if the string contains a whole number (integer):

string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);

The TryParse method will try to convert the string to a number (integer) and if it succeeds it will return true and place the corresponding number in myInt. If it can't, it returns false.

Solutions using the int.Parse(somString) alternative shown in other responses works, but it is much slower because throwing exceptions is very expensive. TryParse(...) was added to the C# language in version 2, and until then you didn't have a choice. Now you do: you should avoid the Parse() alternative.

If you want to accept decimal numbers, the decimal class also has a .TryParse(...) method. Replace int with decimal in the above discussion, and the same principles apply.

Euro Micelli
+1 for mentioning Parse() vs TryParse()
Lucas
+6  A: 
nmiranda
referencing Microsoft.VisualBasic.dll from C# app? eww :P
Lucas
I have no problem to use "IsNumeric" it works good. Also you can see that there's little efficience difference between TryParse and IsNumeric. Remember that TryParse is new in 2.0 and before then it was better to use IsNumeric that any other strategy.
nmiranda
Well, VB.NET's IsNumeric() internally uses double.TryParse(), after a number of gyrations that are needed (among other things) for VB6 compatibility. If you don't need compatibility, double.TryParse() is just as simple to use, and it saves you from wasting memory by loading Microsoft.VisualBasic.dll in your process.
Euro Micelli
A: 

Here is the C# method. Int.TryParse Method (String, Int32)

Syed Tayyab Ali
you could at least mention the method name in your answer...
Lucas
method name specified!
Syed Tayyab Ali
+4  A: 

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.

John M Gant