[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 153
  • Last Modified:

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



0
directxBOB
Asked:
directxBOB
  • 2
1 Solution
 
Jai STech 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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now