Search code examples
javastring-formatting

String Format an integer to look like a social security number


After the users input of a social security number I would like to take the integer that is entered and display is as a social security number. So that XXXXXXXXX becomes XXX-XX-XXXX.

 public String getSSNumber()
        {      
            String convert;
            convert = String.valueOf(ssNumber);
            return convert;
        }

 public String toString()
        {
           return (" SSN: " + String.format("%03d-%02d-%04d", ssNumber);
        }

This is the code I tried, and I just can't seem to get it to work. Forgive the gross code I'm a new student to java.


Solution

  • String.format is the wrong tool for the job. It cannot do what you want. Java sees 3 %d values and thus wants you to pass 3 numbers to it.

    You need to do the work of chopping the number into its parts on your own. You can either use integer wrangling for it, or string wrangling.

    int wrangling

    .. though you may want to use long.

    Given 123456789, you need to obtain:

    • 123
    • 45
    • 6789

    To that, you can divide by the relevant number: 123456789 / 1000000 is 123.

    For 45, you need to combine modulo and division. First, you want to lop off the 123, which requires modulo, then lop off the 6789 which requires division. 123456789 % 1000000 is 3456789. Divide that by 10000 and you get 45. Alternatively, keep 'updating' the number: Once you get 123 out subtract that times 1000000.

    long ssn = 123_45_6789L;
    int p1 = ssn / 1_00_0000;
    int p2 = (ssn % 1_00_0000) / 1_0000;
    int p3 = ssn % 1_0000;
    return String.format("%03d-%02d-%04d", p1, p2, p3);
    

    String wrangling

    (EDIT: Replaced with @OleV.V.'s far more elegant take).

    First turn your number into a string then inject the dashes:

    long ssn = 123456789L;
    String a = String.format("%09d", ssn)
      .replaceFirst("(\\d{3})(\\d{2})(\\d{4})", "$1-$2-$3");
    

    either one works fine - but the second (string wrangling) example strikes me as more readable.