Search Amazon:

Test whether a string value is numeric in C#

VB provides the IsNumeric function to test whether a string contains a valid numeric value or not. C# has no such function leaving you to write your own. Here is the most common approach:

    public static bool IsDecimal(string theValue
    {
        try
        {
            Convert.ToDouble(theValue);
            return true;
        } 
        catch 
        {
            return false;
        }
    } //IsDecimal

    public static bool IsInteger(string theValue)
    {
        try
        {
            Convert.ToInt32(theValue);
            return true;
        } 
        catch 
        {
            return false;
        }
    } //IsInteger

Another way is to use Regular Expressions to test that the string contains only digit characters.:

    private static Regex _isNumber = new Regex(@"^\d+$");

    public static bool IsInteger(string theValue)
    {
        Match m = _isNumber.Match(theValue);
        return m.Success;
    } //IsInteger

Sign In
  User Id 
  Password 


Submit Your Own Code and Articles




About TheScarms
About TheScarms

Ask me your programming questions

I read every email and answer all I can.

User Feedback: Be the first to add a comment! Items to Show:     

     
You must log in to post feedback.
Comment:    
 

If you use this code, please mention "www.TheScarms.com"

Email this page


TheScarms AppSentinel lets you securely copy protect and create evaluation versions of your software

TheScarms(tm) AppSentinel lets you quickly and easily create evaluation versions of your software and stop unauthorized copying and unregistered use of your programs!

Get your free
trial copy today!


      The World's Number 1 Web Host

© Copyright 2008 TheScarms