How to check if string is number (IsNumeric) in C#?


I have a string "123" and another string "Test", now I want to identify from which you these string conatins number, so How can i check if string is a number or not in C#, is there any method in C# or we need to create custom method for it?

Example :

"11" = true

"Hello"= false


Asked by:- bhanu
0
: 158 At:- 5/1/2020 7:33:54 AM
C# IsNumeric C#






1 Answers
profileImage Answered by:- vikas_jk

Yes, you can do it using TryParse in C# 7 or above

int n;
bool isNumeric = int.TryParse("11", out n);
Console.WriteLine(isNumeric);

OR

Check if string is Numeric using Regular expression

var RegexCheck=Regex.IsMatch("11", @"^\d+$");
Console.WriteLine(RegexCheck);

OR

Create a Custom Method

public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }

Here is the Complete C# Console example

using System;
using System.Text.RegularExpressions;
					
public static class Program
{
	public static void Main()
	{
		int n;
        bool isNumeric = int.TryParse("11", out n);
		Console.WriteLine(isNumeric);
		
		//using Regular Expression
		var RegexCheck=Regex.IsMatch("11", @"^\d+$");
		Console.WriteLine(RegexCheck);
		
		//Using Custom Method
		Console.WriteLine(IsNumeric("Test"));
		Console.WriteLine(IsNumeric("11.3"));
	}
	public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

Output:

True
True
False
True

You can try it here: https://dotnetfiddle.net/YZMP4w

Hope it helps.

1
At:- 5/1/2020 8:00:52 AM
I tried the first way "bool isNumeric = int.TryParse("11", out n);" and it works for me, thanks 0
By : bhanu - at :- 5/20/2020 7:30:36 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly