Applying Flags in Real-world Examples
Now that we've covered the basics of printf()
formatting and the available flags, let's explore some real-world examples of how you can apply these flags to improve the readability and presentation of your output.
When dealing with currency values, it's often desirable to display them with a consistent format, including the currency symbol, thousands separators, and decimal places.
double amount = 12345.67;
System.out.printf("Total: $%,.2f%n", amount);
Output:
Total: $12,345.67
In this example, the %,.2f
format specifier uses the ,
flag to add a thousands separator and the .2f
specifier to display the amount with two decimal places.
Aligning Tabular Data
Flags can be particularly useful when you need to display data in a tabular format. By using the -
flag for left-alignment, you can create well-organized and visually appealing tables.
System.out.printf("%-20s %-10s %-10s%n", "Product", "Price", "Quantity");
System.out.printf("%-20s %-10.2f %-10d%n", "LabEx Notebook", 29.99, 15);
System.out.printf("%-20s %-10.2f %-10d%n", "LabEx Pen", 2.50, 50);
System.out.printf("%-20s %-10.2f %-10d%n", "LabEx Highlighter", 4.75, 25);
Output:
Product Price Quantity
LabEx Notebook 29.99 15
LabEx Pen 2.50 50
LabEx Highlighter 4.75 25
When displaying percentages, you can use the %
format specifier along with the desired number of decimal places.
double percentage = 0.8765;
System.out.printf("Completion: %.2f%%%n", percentage * 100);
Output:
Completion: 87.65%
By using the %.2f%%
format specifier, the output displays the percentage value with two decimal places, followed by the percent symbol.
These examples demonstrate how you can leverage the various flags in printf()
formatting to create more organized, informative, and visually appealing output in your Java applications.