简体   繁体   中英

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?

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 .

You can do like...

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

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

Have a look at this question:

What is the C# equivalent of NaN or IsNumeric?

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM