Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

asp.net

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?

like image 618
satyajit Avatar asked May 26 '11 11:05

satyajit


2 Answers

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.

like image 52
Darin Dimitrov Avatar answered Sep 18 '22 10:09

Darin Dimitrov


You can do like...

 string s = "sdf34";
    Int32 a;
    if (Int32.TryParse(s, out a))
    {
        // Value is numberic
    }  
    else
    {
       //Not a valid number
    }
like image 42
Muhammad Akhtar Avatar answered Sep 17 '22 10:09

Muhammad Akhtar