Rounding and locales: %f, DecimalFormat, MessageFormat, HexFormat
A single quote in MessageFormat starts a quoted section, which swallowed the {1}. Write '' for an apostrophe.
String.format, printf and formatted build text from a template with placeholders like %s, %d and %.2f, giving you control over width, alignment, padding, decimals and grouping. Pass a Locale for numbers, because the decimal and thousands separators change by country.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Print a multiplication table for 1 to 4 where every number is right-aligned in a 4-character column.
Write static String bar(String label, int percent) that prints label left-aligned in 8 characters, then percent right-aligned in 3 characters followed by %, then that many # characters divided by 10. Print it for cpu 72 and memory 35.
Format the number of bytes 1536000 as a human-readable size with one decimal place: 1.5 MB (use 1024-based units and Locale.ROOT).
Explain it without notes
Describe the full syntax of a format specifier and give an example using every part.
What is the difference between width and precision for %s and %f?
Why should you pass a Locale to String.format, and which one?
How does %.2f round, and how does that differ from DecimalFormat?
Which exceptions can formatting throw, and when do you find out about them?
Expected output
%.2f of 0.125: 0.13
%.1f of 0.25: 0.3
%.2f of 1.005: 1.01
DecimalFormat of 0.25 (HALF_EVEN): 0.2
DecimalFormat of 1234567.89: 1,234,567.9
ROOT: 1,234.50
GERMANY: 1.234,50
Asha has 3 items
Ashas cart has {1} items
Asha's cart has 3 items
HexFormat: 1A:2B:FF