Java: parse int value from a char
Here's the quick and easy way to convert a digit char to int:
Or apply:
The int squeezed from a char digit is obtained using both methods.
Parsing numbers from hieroglyphs
If you're playing with non-Latin numerals, this is where Character.getNumericValue()
starts moonwalking:
Sans Excel, but ensures your app speaks Universal Cuneiform.
Handling surprise elements - non-numeric characters
While parsing integers from characters is like a walk in the park, meeting a non-numeric character could feel like stumbling upon a bear. It's betchar
to check first with Character.isDigit()
:
This quick check ensures the bear's more scared of you than you are of it.
Catch them all - parsing numbers from entire strings
It's not Pokemon, but here's how to catch every digit from a string and add them:
With a single Pokeball, you catch all the numbers and make honey out of them. Original bear is nowhere in sight!
ASCII - When speed is key
Life in the fast lane with ASCII characters and the - '0'
trick:
This condition checks for numeric ASCII characters, faster than Sonic the Hedgehog, without needing extra method calls.
Alpha to Hexa - Parsing strings in different bases
Let's get hexy with numbers in hexadecimal or other bases:
With Integer.parseInt(String, int radix)
you can be a magician and convert a string representation of a number in any base to a decimal form. Abracadabra!
Just remember to pull a NumberFormatException
out of your magician's hat for any invalid input.
Was this article helpful?