Search code examples
javaintegerdoubleprintln

Extract the last 2 digits of an integer (Java)


I have some code that takes an integer and extracts the last 2 numbers and prints them. For example, if I input 10000001, 01 should be the printout/ output. The problem here is that for some reason the output of the program is 1. I am not sure why the output shows up as a single digit.

public class Main {
  public static void main(String[] args) {
    double num = 10000001;
    double digit = num % 100;
    System.out.println(digit);    
  }
} 

Solution

  • Your problem is simple and has a simple answer. In java int num = 1; is same as int num = 01; (both mean same 1 for the compiler) so when you are using % 100 with your number it returns 01 which is nothing but 1 for java as you are storing it to a double data type variable (actually when you use double in this line double digit = num % 100; it prints 1.0 , so you should use int here int digit = num % 100; to remove the decimal point). So using int digit = num % 100; will work and give you desired results with all number except numbers having a 0 before a number.

    To solve your problem completely you can use String class.

    String str = num+""; //connverting int to string
    String digit = str.substring(str.length()-2, str.length());