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
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.
Above solution works as needed but I would like to add another method, which works best for only numbers (no decimal or currency alolowed).
You can create a function to check all characters of string are numbers or not, here is C# function
public bool IsOnlyNumbers(string value)
{
return value.All(char.IsNumber);
}
You would have to add reference "using System.Linq
"
Example
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine(IsNumeric("123"));
Console.WriteLine(IsNumeric("1a3"));
Console.WriteLine(IsNumeric("xx223.2"));
Console.WriteLine(IsNumeric("22.0"));
}
public static bool IsNumeric(string value)
{
return value.All(char.IsNumber);
}
}
Output:
True
False
False
False
Fiddle https://dotnetfiddle.net/45EqlH
As "22.0
" has decimal it will return false
.
You can also use Below Code to check if string is number
Console.WriteLine(Microsoft.VisualBasic.Information.IsNumeric("11")); //true
Console.WriteLine(Microsoft.VisualBasic.Information.IsNumeric("bbb")); //false
Console.WriteLine(Microsoft.VisualBasic.Information.IsNumeric("11.334")); //true
You will have to add reference of "Microsoft.VisualBasic
" to use above code, which you can do by right-clicking "Reference" -> "Add-Reference"
OR
You can check each char of a string
public static bool CheckIfNumeric(string s)
{
foreach (char c in s)
{
if (!char.IsDigit(c) && c != '.')
{
return false;
}
}
return true;
}
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly