I’m trying to extract the numeric value from a character in Java. For example, if I have char x = '9';
, how do I convert that to the integer 9?
I tried casting, but it didn’t give the expected result. What’s the right way to handle char to int Java conversion when the char represents a digit?
When I need to convert a character like ‘9’ to the integer 9, I use:
int num = Character.getNumericValue('9');
It’s super safe, it handles not just digits but even characters like Roman numerals or Unicode digits.
It’s my go-to when I’m parsing user input character-by-character.
If I’m sure the character is a digit between ‘0’ and ‘9’, I just subtract ‘0’ like this:
char x = '9';
int num = x - '0';
This works because of ASCII values, ‘9’ is 57 and ‘0’ is 48, so the result is 9. It’s super fast and lightweight, perfect for parsing strings of digits.
Sometimes I convert the char to a String and then parse it:
char x = '9';
int num = Integer.parseInt(String.valueOf(x));
This is overkill for single characters, but I use it when dealing with dynamic data or when writing cleaner, more readable code that non-Java folks can also follow easily.