I was wondering if anyone knew how to use mathematics to truncate a number from the left (remove digits one by one starting from the left).
I can use a simple division to truncate digits from the right:
int num = 10098;
while (num > 0){
System.out.println(num);
num /= 10;
}
This will output what I want:
10098
1009
100
10
1
But does anyone know a way to do this the other way around on integers and to truncate digits from the left without converting to String?
Try n = n % (int) Math.pow(10, (int) Math.log10(n));
. Found here.
public void test() {
int n = 10098;
while (n > 0) {
System.out.println("n=" + n);
n = n % (int) Math.pow(10, (int) Math.log10(n));
}
}
prints
n=10098
n=98
n=8