Check if a string is a number in C#
This article illustrates the different techniques to check if a string is a number in C#.
1. Using TryParse() method
You can use the TryParse() method to identify if a string is a number. It works by converting the specified string to equivalent signed integer representation and returns true if the conversion succeeded; otherwise, false. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { string s = "123"; int n; bool isNumeric = int.TryParse(s, out n); Console.WriteLine(n); // 123 Console.WriteLine(isNumeric); // True } } |
Note that the TryParse() method takes an Out parameter, which stores the integer value if the conversion was a success. This can be shortened to below if the Out parameter is not needed.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = "123"; bool isNumeric = int.TryParse(s, out _); Console.WriteLine(isNumeric); // True } } |
Note that the Out parameter is declared and initialized in separate statements. Starting with C# 7, we can in-line declare and initialize the Out parameter.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string s = "123"; bool isNumeric = int.TryParse(s, out int n); Console.WriteLine(n); // 123 Console.WriteLine(isNumeric); // True } } |
2. Using Char.IsDigit() method
The Char.IsDigit() method returns a boolean value indicating if the specified character is a digit. The following code example demonstrates the usage of the Char.IsDigit() method with the Enumerable.All() method to determine if a string is a number.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { string s = "123"; bool isNumeric = s.All(char.IsDigit); Console.WriteLine(isNumeric); // True } } |
3. Using Regex.IsMatch() method
Finally, you can use the regular expression to check if a string is numeric. This can be done using the Regex.IsMatch() method, which determines if the specified string matches with the supplied regex. This is demonstrated below. Note that ^ matches with the beginning of the string and $ match with its end.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string s = "123"; bool isNumeric = Regex.IsMatch(s, @"^\d+$"); Console.WriteLine(isNumeric); // True } } |
That’s all about checking if a string is a number in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)