Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the second digit from a long variable [duplicate]

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.

like image 412
shree Avatar asked Dec 26 '17 08:12

shree


4 Answers

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));
like image 133
Suresh Atta Avatar answered Nov 17 '22 11:11

Suresh Atta


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)):
like image 42
Ankit jain Avatar answered Nov 17 '22 11:11

Ankit jain


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));
like image 5
Ousmane D. Avatar answered Nov 17 '22 11:11

Ousmane D.


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.

like image 3
Shen Yudong Avatar answered Nov 17 '22 12:11

Shen Yudong