Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting SSN using String.format

I am currently using a random genertor to generator numbers 9 digit numbers for me. I am currently trying to use String.format, in java, to print the random numbers like this XXX-XX-XXXX which is like a social security number. I simply cant do it and i not sure how to do. I am using modulo and it seems my padding are off or i am just completely wrong. The issues is that i have to use modulo. Any assistance pointing me to the right direction is much appreciated, thank you. I am trying to fix the ID.

public  String toString (){

        System.out.printf("%d\n",ID);

        return  String.format("First Name: %12s LastName %12s ID: %03d-%02d-%04d ", firstName, lastName,ID%1000,ID%10000, ID%000001000);

    }
}
like image 678
m0d3r Avatar asked Jan 29 '17 23:01

m0d3r


2 Answers

Basically you need two steps instead of one:

  1. Divide the number by 10^X to remove the last X digits. (N / 10^X)
  2. Get the number modulo 10^Y to take the last Y digits. (N % 10^Y)

Modified Code

public static int getDigits(int num, int remove, int take) {
    return (num / (int)Math.pow(10, remove)) % (int)Math.pow(10, take);
}

public String toString() {
    return  String.format("First Name: %12s LastName %12s ID: %03d-%02d-%04d ",
                          firstName, lastName,
                          getDigits(ID, 6, 3), getDigits(ID, 4, 2), getDigits(ID, 0, 4));
}

Alternative Solution

Convert the number to String and use String.substring to cut the relevant pieces

public String toString() {
    String IdStr = String.valueOf(ID);
    return  String.format("First Name: %12s LastName %12s ID: %03d-%02d-%04d ",
                          firstName, lastName,
                          IdStr.substring(0, 3), IdStr.substring(3, 5), IdStr.substring(5, 9));
}
like image 86
Hesham Attia Avatar answered Nov 14 '22 23:11

Hesham Attia


Try doing

return  String.format("First Name: %12s LastName %12s ID: %03d-%02d-%04d ", firstName, lastName,(int)ID/1000000,(int)(ID%1000000)/10000, ID%10000);
like image 39
Locke Avatar answered Nov 14 '22 22:11

Locke