tags:

views:

213

answers:

9

I need to check if a string contains only digits. How could I achieve this in C#?

string s = "123"    → valid 
string s = "123.67" → valid 
string s = "123F"   → invalid 

Is there any function like IsNumeric?

+4  A: 
double n;
if (Double.TryParse("128337.812738", out n)) {
  // ok
}

works assuming the number doesn't overflow a double

for a huge string, try the regexp:

if (Regex.Match(str, @"^[0-9]+(\.[0-9]+)?$")) {
  // ok
}

add in scientific notation (e/E) or +/- signs if needed...

jspcal
What Should be the parameter? Will it accept a huge string ? are there any limitations ?
Maneesh
for a huge string you need a regexp
jspcal
Thanks the reg Exp solution works! Thanks jspcal
Maneesh
A: 

I think you can use Regular Expressions, in the Regex class

Regex.IsMatch( yourStr, "\d" )

or something like that off the top of my head.

Or you could use the Parse method int.Parse( ... )

JustAPleb
A: 

This should work:

bool isNum = Integer.TryParse(Str, out Num);
Kolky
Int.TryParse will fail on his third test case of "123.67"
ZombieSheep
A: 

You can use double.TryParse

string value;
double number;

if (Double.TryParse(value, out number))
   Console.WriteLine("valid");
else
   Console.WriteLine("invalid");
Gregory Pakosz
+2  A: 

Taken from MSDN (How to implement Visual Basic .NET IsNumeric functionality by using Visual C#):

// IsNumeric Function
static bool IsNumeric(object Expression)
{
    // Variable to collect the Return value of the TryParse method.
    bool isNum;

    // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
    double retNum;

    // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
    // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
    isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
    return isNum;
}
jbloomer
A: 

This should work no matter how long the string is:

string s = "12345";
bool iAllNumbers = s.ToCharArray ().All (ch => Char.IsDigit (ch) || ch == '.');
Tarydon
That would also match "123.456.789", which is not a valid number
Philippe Leybaert
@Philippe: You are correct. I think the RegExp is the cleanest way to go here.
Tarydon
+1  A: 

Using regular expressions is the easiest way (but not the quickest):

bool isNumeric = Regex.IsMatch(s,@"^(\+|-)?\d+(\.\d+)?$");
Philippe Leybaert
You are missing the `.23` case.
leppie
Possibly, if you want to allow numbers that were used by Commodore 64 computers 25 years ago :-)
Philippe Leybaert
Sorry buddy, but C# accepts it too, and so does Scheme, and most languages with IEEE floating-point :)
leppie
I'm not saying C# doesn't accept it. It's just not something an average user would type when entering a number. I'd rather not accept it as valid input from a user, but that's just my opinion.
Philippe Leybaert
A: 

If you are receiving the string as a parameter the more flexible way would be to use regex as described in the other posts. If you get the input from the user, you can just hook on the KeyDown event and ignore all keys that are not numbers. This way you'll be sure that you have only digits.

Adrian Faciu
A: 

As stated above you can use double.tryParse

If you don't like that (for some reason), you can write your own extension method:

    public static class ExtensionMethods
    {
        public static bool isNumeric (this string str)
        {
            for (int i = 0; i < str.Length; i++ )
            {
                if ((str[i] == '.') || (str[i] == ',')) continue;    //Decide what is valid, decimal point or decimal coma
                if ((str[i] < '0') || (str[i] > '9')) return false;
            }

            return true;
        }
    }

Usage:

string mystring = "123456abcd123";

if (mystring.isNumeric()) MessageBox.Show("The input string is a number.");
else MessageBox.Show("The input string is not a number.");

Input :

123456abcd123

123.6

Output:

false

true

Rekreativc