How to isolate digits in a long variable for JAVA?
long 122343434434
how to isolate the 2nd number?

Recommended Answers

long anumber = 122335574;
while (anumber>99) {
  anumber /= 10;
}
int seconddigit = anumber % 10;

Another way to do it is to convert the number to String and then use the charAt() method of the String. Then convert it back to integer...


       
Jump to Post

All 3 Replies

One way to do is to keep dividing it by 10 until you get to the digit number you want?

how do i do that to find the second number though?

long anumber = 122335574;
while (anumber>99) {
  anumber /= 10;
}
int seconddigit = anumber % 10;

Another way to do it is to convert the number to String and then use the charAt() method of the String. Then convert it back to integer...

long anumber = 122335574;
Long lnumber = new Long(anumber);
String snumber = lnumber.toString();
int seconddigit = snumber.charAt(1)-48;

PS: Both ways don't guarantee when the number is less than 10.
The string way doesn't guarantee when the number is negative. However, could easily be fixed by converting the number to positive first.

commented: Solid post :) +14
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.