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: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Formatting Numeric Print Output: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

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