Ensuring my String only contains numbers.

I was just wondering what is the easiest way to check to ensure a string only contains numbers.

I was thinking that perhaps

Convert.ToInt16(myString);

But perhaps there is a better way



directxBOBAsked:
Who is Participating?
 
Jai SConnect With a Mentor Tech ArchCommented:
use this ...much more effective

public bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
{
    Double result;
    return Double.TryParse(val,NumberStyle,System.Globalization.CultureInfo.CurrentCulture,out result);
}
0
 
Jai STech ArchCommented:
you can also use regular expressions

using System.Text.RegularExpressions;

 string MyString = "234234234";
            if (Regex.IsMatch(MyString, @"^-?(\d+)(\.\d*)?$"))
                MessageBox.Show(MyString + " is numeric");
0
 
bungHocCommented:
Regular expressions:

string str = "\x1811\x1812\x1813";
Regex reNum = new Regex(@"^\d+$");
bool isNumeric = reNum.Match(strToTest).Success;

Regular expression \d digit character will match any Unicode digit.

Hope this helps
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.