Convert char to int in C#
This post will discuss how to convert a char to int in C#.
1. Using Char.GetNumericValue()
method
The recommended approach is to use the in-built GetNumericValue() method to convert a numeric Unicode character to its numeric equivalent.
The following example demonstrates the working of the GetNumericValue()
method. It expects a char representation of a numeric value and returns a double value. A cast is needed to convert the double value to an int.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { char ch = '9'; int intVal = (int)Char.GetNumericValue(ch); Console.WriteLine(intVal); } } /* Output: 9 */ |
2. Difference with ‘0’
We know that each of the ASCII characters is represented by values from 0 through 127. To get the integer equivalent of characters ‘0’ to ‘9’, simply subtract ‘0’ from it. The following code example shows how to implement this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { char ch = '9'; int intVal = ch - '0'; Console.WriteLine(intVal); } } /* Output: 9 */ |
3. Using CharUnicodeInfo.GetDecimalDigitValue()
method
Another approach is to use the CharUnicodeInfo.GetDecimalDigitValue() method, which returns the decimal digit value of the specified numeric Unicode character. This method is demonstrated below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Globalization; public class Example { public static void Main() { char ch = '9'; int intVal = CharUnicodeInfo.GetDecimalDigitValue(ch); Console.WriteLine(intVal); } } /* Output: 9 */ |
4. Using Int32.Parse()
method
The following code example demonstrates how to use Int32.Parse() and Int32.TryParse()
to convert char to its integer equivalent.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { char ch = '9'; int intVal = int.Parse(ch.ToString()); Console.WriteLine(intVal); } } /* Output: 9 */ |
That’s all about converting char to int 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 :)