In this program, you’ll learn to check if a string is numeric or not in C#.
Code: Check if a string is numeric
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Program { static void Main(string[] args) { string text = "144,52"; bool numeric = true; try { Double num = Double.Parse(text); } catch (Exception e) { numeric = false; } if (numeric) Console.WriteLine("{0} is a number",text); else Console.WriteLine("{0} is not a number", text); Console.ReadLine(); } } |
In the above program, we’ve a text named string which contains the string to be checked. We also have a bool value numeric which stores if the final result is numeric or not.
To check if string contains numbers only, in the try block, we use Double’s Parse() method to convert the string to a Double.
If it throws an error , it means string isn’t a number and numeric is set to false. Else, it’s a number.
Output: