I am trying to fetch second digit from a long variable.
long mi = 110000000;
int firstDigit = 0;
String numStr = Long.toString(mi);
for (int i = 0; i < numStr.length(); i++) {
System.out.println("" + i + " " + numStr.charAt(i));
firstDigit = numStr.charAt(1);
}
When I am printing firstDigit = numStr.charAt(1)
on console. I am getting 1
which is expected but when the loop finishes firstDigit
has 49
.
Little confused why.
Because 49 is the ASCII value of char '1'.
So you should not assign a char to int directly.
And you don't need a loop here which keeps ovveriding the current value with charAt(1)
anyway.
int number = numStr.charAt(1) - '0'; // substracting ASCII start value
The above statement internally works like 49 -48 and gives you 1.
If you feel like that is confusious, as others stated use Character.getNumericValue();
Or, although I don't like ""+
hack, below should work
int secondDigit = Integer.parseInt("" + String.valueOf(mi).charAt(1));
You got confused because 49 is ASCII value of integer 1. So you may parse character to integer then you can see integer value.
Integer.parseInt(String.valueOf(mi).charAt(1)):
You're probably looking for Character.getNumericValue(...)
i.e.
firstDigit = Character.getNumericValue(numStr.charAt(1));
Otherwise, as the variable firstDigit
is of type int
that means you're assigning the ASCII representation of the character '1' which is 49 rather than the integer at the specified index.
Also, note that since you're interested in only a particular digit there is no need to put the statement firstDigit = numStr.charAt(1);
inside the loop.
rather, just do the following outside the loop.
int number = Character.getNumericValue(numStr.charAt(1));
you only need define firstDigit as a char type variable, so will print as character. since you define as int variable, it's value is the ASCII value of char '1': 49. this is why you get 49 instead of 1.
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