I wrote some code to convert my hexadecimal display string to decimal integer. However, when input is something like 100a or 625b (something with a letter) I got an error like this:
java.lang.NumberFormatException: For input string: " 100a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source)
How can I convert my string with letters to a decimal integer?
if(display.getText() != null)
{
if(display.getText().contains("a") || display.getText().contains("b") ||
display.getText().contains("c") || display.getText().contains("d") ||
display.getText().contains("e") || display.getText().contains("f"))
{
temp1 = Integer.parseInt(display.getText(), 16);
temp1 = (double) temp1;
}
else
{
temp1 = Double.parseDouble(String.valueOf(display.getText()));
}
}
It looks like there's an extra (leading) space character in your string (" 100a"). You can use trim()
to remove leading and trailing whitespaces:
temp1 = Integer.parseInt(display.getText().trim(), 16);
Or if you think the presence of a space means there's something else wrong, you'll have to look into it yourself, since we don't have the rest of your code.
public static int hex2decimal(String s) {
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
That's the most efficient and elegant solution I have found on the Internet. Some of the other solutions provided here didn't always work for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With