satyajit
satyajit

Reputation: 2700

c# code to check whether a string is numeric or not

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?

Upvotes: 5

Views: 53410

Answers (11)

Rana Bhopale
Rana Bhopale

Reputation: 51

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!!

Upvotes: 0

Anand Mohan
Anand Mohan

Reputation: 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.");

Upvotes: -1

Dipitak
Dipitak

Reputation: 97

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);

Upvotes: 0

Jithi Vasudev
Jithi Vasudev

Reputation: 13

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");

Upvotes: 0

ofirbt
ofirbt

Reputation: 1886

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.

Upvotes: 0

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

You can do like...

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

Upvotes: 6

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 19

AjayR
AjayR

Reputation: 4179

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;
            }
        }

Upvotes: 0

Jon Egerton
Jon Egerton

Reputation: 41539

Have a look at this question:

What is the C# equivalent of NaN or IsNumeric?

Upvotes: 1

ChristiaanV
ChristiaanV

Reputation: 5541

You can use Int32.TryParse()

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

Upvotes: 4

pabdulin
pabdulin

Reputation: 35219

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

Upvotes: 2

Related Questions