5

I am using Visual Studio 2010.I want to check whether a string is numeric or not.Is there any built in function to check this or do we need to write a custom code?

2
  • The people pointing you towards TryParse are correct, but keep in mind that the default is to parse with the current culture active for that request on the server. If you expect a specific culture, you need to pass this in explicitly. Commented May 26, 2011 at 12:03
  • 1
    Why did you accept the worst answer? Commented May 26, 2011 at 13:19

11 Answers 11

19

You could use the int.TryParse method. Example:

string s = ...
int result;
if (int.TryParse(s, out result))
{
    // The string was a valid integer => use result here
}
else
{
    // invalid integer
}

There are also the float.TryParse, double.TryParse and decimal.TryParse methods for other numeric types than integers.

But if this is for validation purposes you might also consider using the built-in Validation controls in ASP.NET. Here's an example.

Sign up to request clarification or add additional context in comments.

2 Comments

That will only cover int though, there are lots of other numerics.
@Jon Egerton, I've updated my answer to take your remark into account.
6

You can do like...

 string s = "sdf34";
    Int32 a;
    if (Int32.TryParse(s, out a))
    {
        // Value is numberic
    }  
    else
    {
       //Not a valid number
    }

1 Comment

'numeric' should also include decimal numbers
4

You can use Int32.TryParse()

http://msdn.microsoft.com/en-us/library/f02979c7.aspx

Comments

2

Yes there is: int.TryParse(...) check the out bool param.

Comments

1

Have a look at this question:

What is the C# equivalent of NaN or IsNumeric?

Comments

0

You can use built in methods Int.Parse or Double.Parse methods. You can write the following function and call where ever necessary to check it.

public static bool IsNumber(String str)
        {
            try
            {
                Double.Parse(str);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

1 Comment

Since 2005 (.NET 2.0) there are TryParse methods - don't use exceptions for normal program flow!
0

The problem with all the Double/Int32/... TryParse(...) methods is that with a long enough numeric string, the method will return false;

For example:

var isValidNumber = int.TryParse("9999999999", out result);

Here, isValidNumber is false and result is 0, although the given string is numeric.

If you don't need to use the string as int, I would go with regular expressions validation on this one:

var isValidNumber = Regex.IsMatch(input, @"^\d+$")

This will only match integers. "123.45" for example, will fail.

If you need to check for floating point numbers:

var isValidNumber = Regex.IsMatch(input, @"^[0-9]+(\.[0-9]+)?$")

Note: try to create a single Regex object and send it to your int testing method for better performance.

Comments

0

Try this:

string Str = textBox1.Text.Trim();
double Num;
bool isNum = double.TryParse(Str, out Num);
if (isNum)
    MessageBox.Show(Num.ToString());
else
    `enter code here`MessageBox.Show("Invalid number");

Comments

0

Use IsNumeric() to check whether given string is numeric or not. It always return True for numeric value regardless whether it is Int or Double.

string val=...; 
bool b1 = Microsoft.VisualBasic.Information.IsNumeric(val);

Comments

0
using System;

namespace ConsoleApplication1
{
    class Test
    {

        public static void Main(String[] args)
        {
            bool check;
            string testStr = "ABC";
            string testNum = "123";
            check = CheckNumeric(testStr);
            Console.WriteLine(check);
            check = CheckNumeric(testNum);
            Console.WriteLine(check);
            Console.ReadKey();

        }

        public static bool CheckNumeric(string input)
        {
            int outPut;
            if (int.TryParse(input, out outPut))
                return true;

            else
                return false;
        }

    }
}

This will work for you!!

Comments

-1

Try This-->

String[] values = { "87878787878", "676767676767", "8786676767", "77878785565", "987867565659899698" };

if (Array.TrueForAll(values, value =>
{
    Int64 s;
    return Int64.TryParse(value, out s);
}
))

Console.WriteLine("All elements are  integer.");
else
Console.WriteLine("Not all elements are integer.");

1 Comment

Why Int64? What about double?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.