How do I properly align using String.format in Java?

14,063

Solution 1

Use fixed size format:

Using format strings with fixed size permits to print the strings in a table-like appearance with fixed size columns:

String rowsStrings[] = new String[] {"1", 
                                     "1234", 
                                     "1234567", 
                                     "123456789"};

String column1Format = "%-3.3s";  // fixed size 3 characters, left aligned
String column2Format = "%-8.8s";  // fixed size 8 characters, left aligned
String column3Format = "%6.6s";   // fixed size 6 characters, right aligned
String formatInfo = column1Format + " " + column2Format + " " + column3Format;

for(int i = 0; i < rowsStrings.length; i++) {
    System.out.format(formatInfo, rowsStrings[i], rowsStrings[i], rowsStrings[i]);
    System.out.println();
} 

Output:

1   1             1
123 1234       1234
123 1234567  123456
123 12345678 123456

In your case you could find the maximum length of the strings you want to display and use that to create the appropriate format information, for example:

// find the max length
int maxLength = Math.max(a.length(), b.length());

// add some space to separate the columns
int column1Length = maxLength + 2;

// compose the fixed size format for the first column
String column1Format = "%-" + column1Length + "." + column1Length + "s";

// second column format
String column2Format = "%10.2f";

// compose the complete format information
String formatInfo = column1Format + " " + column2Format;

System.out.format(formatInfo, a, price);
System.out.println();
System.out.format(formatInfo, b, price);

Solution 2

Put negative sign in front of your format specifier so instead of printing 5 spaces to the left of your float value, it adjusts the space on the right until you find the ideal position. It should be fine

Share:
14,063
blyter
Author by

blyter

Updated on June 05, 2022

Comments

  • blyter
    blyter almost 2 years

    Let's say I have a couple variable and I want to format them so they're all aligned, but the variables are different lengths. For example:

    String a = "abcdef";
    String b = "abcdefhijk";
    

    And I also have a price.

    double price = 4.56;
    

    How would I be able to format it so no matter how long the String is, they are aligned either way?

    System.out.format("%5s %10.2f", a, price);
    System.out.format("%5s %10.2f", b, price);
    

    For example, the code above would output something like this:

    abcdef       4.56
    abcdefhijk       4.56
    

    But I want it to output something like this:

    abcdef      4.56
    abcdefhijk  4.56
    

    How would I go about doing so? Thanks in advance.