Explain Codes LogoExplain Codes Logo

Java: parse int value from a char

java
parse-int-value
character-getnumericvalue
ascii-trick
Anton ShumikhinbyAnton Shumikhin·Oct 17, 2024
TLDR

Here's the quick and easy way to convert a digit char to int:

char squeeze = '5'; // chosen by my cat walking on the keyboard int juice = squeeze - '0'; // Result: 5, cat-approved

Or apply:

int juice = Character.getNumericValue(squeeze); // Result: 5, it's the same universe

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:

char hieroglyph = '६'; // Sanskrit numerals used before Excel was invented int number = Character.getNumericValue(hieroglyph); // Result: 6, surprisingly

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():

char grizzly = '@'; if(Character.isDigit(grizzly)) { int run = grizzly - '0'; // Good luck outrunning this bear } else { // Run away like the wind }

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:

String forest = "b1e2a3r4s"; // Someone spelled bear using numbers, clever! int honey = 0; // Start without any honey // Catch all the numbers (honey) using a Pokeball (loop) for (int i = 0; i < forest.length(); i++) { if (Character.isDigit(forest.charAt(i))) { honey += forest.charAt(i) - '0'; // Every caught number is made honey } } // Result: honey = 10, that's a lot of honey!

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:

int sum = 0; for(char ch : charArray) { if('0' <= ch && ch <= '9') { sum += ch - '0'; // Adding to the stash like a speedy squirrel } }

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:

String hex = "D"; // Not hexed, just hexadecimal int decimal = Integer.parseInt(hex, 16); // Result: decimal = 13, hexed to normal

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.