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?

Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
satyajit
  • 2,540
  • 11
  • 33
  • 44
  • 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. – Lucero May 26 '11 at 12:03
  • 1
    Why did you accept the *worst* answer? – Lucero May 26 '11 at 13:19

11 Answers11

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
6

You can do like...

 string s = "sdf34";
    Int32 a;
    if (Int32.TryParse(s, out a))
    {
        // Value is numberic
    }  
    else
    {
       //Not a valid number
    }
Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
4

You can use Int32.TryParse()

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

ChristiaanV
  • 5,401
  • 3
  • 32
  • 42
2

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

Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96
1

Have a look at this question:

What is the C# equivalent of NaN or IsNumeric?

Community
  • 1
  • 1
Jon Egerton
  • 40,401
  • 11
  • 97
  • 129
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.

ofirbt
  • 1,846
  • 7
  • 26
  • 41
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");
Яois
  • 3,838
  • 4
  • 28
  • 50
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);
Dipitak
  • 97
  • 1
  • 1
  • 3
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!!

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;
            }
        }
AjayR
  • 4,169
  • 4
  • 44
  • 78
  • 1
    Since 2005 (.NET 2.0) there are `TryParse` methods - don't use exceptions for normal program flow! – Lucero May 26 '11 at 12:02
-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.");
Zsw
  • 3,920
  • 4
  • 29
  • 43