Align printf output in Java

You can try the below example. Do use ‘-‘ before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.

System.out.printf("%2d. %-20s $%.2f%n",  i + 1, BOOK_TYPE[i], COST[i]);

Format String Syntax:

Formatting Numeric Print Output:

PS: This could go as a comment to DwB’s answer, but i still don’t have permissions to comment and so answering it.

Leave a Comment