JAVA Output Alignment

The printf function works fine for space padding. For example:

// % - insert argument value
// , - insert locale-specific separators
// 20 - pad out to 20 spaces
// .2 - fix precision at two decimal places
// s - string argument
// f - float argument
System.out.printf("%20s %20s\n", "Column 1", "Column 2");
System.out.printf("%,20.2f %,20.2f\n", 1034354.54, 243554.4);
System.out.printf("%,20.2f %,20.2f\n", 55553.44, 4325.3);


            Column 1             Column 2
        1,034,354.54           243,554.40
           55,553.44             4,325.30


  • The format specifiers for general, character, and numeric types have the following syntax:

    The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by “1$“, the second by “2$“, etc.

    The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion.

    The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output. When it is negative,  it means align LEFT.

    The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.

    The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument’s data type.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s