Sub topic 11
Formatting Text and Values
Formatting lets you place values into text in a planned way. For example, you can show a price with two digits after the decimal point or line up values in a report.
Java provides String.format to create formatted text. It also provides System.out.printf to print formatted text directly.
The Format String
A format string is text that describes the result you want. It contains placeholders, which are marks that say where values should go.
"%s bought %d items."Here, %s is a placeholder for text, and %d is a placeholder for a whole number. The letter at the end of each placeholder is called a format specifier. It tells Java how to display the value.
Values passed to a method are called arguments. Java normally matches arguments to placeholders in order.
| Placeholder | Use | Example value | Example result |
|---|---|---|---|
| `%s` | Text | `"Mina"` | `Mina` |
| `%d` | A whole number | `3` | `3` |
| `%f` | A floating-point number | `4.5` | `4.500000` |
| `%.2f` | A floating-point number with two digits after the decimal point | `4.5` | `4.50` |
| `%%` | A literal percent sign | No value needed | `%` |
| `%n` | A line break | No value needed | A new line |
A floating-point number is a number stored in a form that can represent fractions. Java’s double type is one kind of floating-point type.
The table shows number results using US-style formatting. Other settings can produce different decimal marks, as you will see later.
A Worked Example
Save this program in a file named FormattingDemo.java. Then run the commands below it.
import java.util.Locale;
public class FormattingDemo {
public static void main(String[] args) {
String name = "Mina";
int count = 3;
double price = 4.5;
String receipt = String.format(
Locale.US,
"%s bought %d items at $%.2f each.",
name, count, price
);
System.out.println(receipt);
System.out.printf(
Locale.US,
"Total: $%.2f%n",
count * price
);
System.out.println(String.format(
Locale.US, "[%8s] [%-8s]", "tea", "tea"
));
System.out.println(String.format(
Locale.US, "[%05d]", 42
));
System.out.println(String.format(
Locale.US,
"First: %1$s; again: %1$s; count: %2$d",
name, count
));
System.out.println(String.format(
Locale.US, "%.4s: %d%%", "pearl", 75
));
System.out.println(String.format(
Locale.US, "US: %,.2f", 12345.5
));
System.out.println(String.format(
Locale.GERMANY, "Germany: %,.2f", 12345.5
));
}
}javac FormattingDemo.java
java FormattingDemoThe output is:
Mina bought 3 items at $4.50 each.
Total: $13.50
[ tea] [tea ]
[00042]
First: Mina; again: Mina; count: 3
pear: 75%
US: 12,345.50
Germany: 12.345,50Look at the first call to String.format:
Locale.USselects US-style number formatting.- The format string describes the text to create.
- The next three arguments fill
%s,%d, and%.2f, in that order. - The method returns the finished string. Returning a string means giving it back to the caller. The program stores it in
receipt.
The call to System.out.printf works much the same way, but it prints the result instead of storing it in a string. It does not add a line break by itself. The %n at the end supplies one.
Control Decimal Places
The placeholder %.2f displays two digits after the decimal point. The .2 is called the precision. For %f, precision sets the number of digits after the decimal point.
| Placeholder | Value | Result with `Locale.US` |
|---|---|---|
| `%f` | `4.5` | `4.500000` |
| `%.2f` | `4.5` | `4.50` |
| `%.0f` | `4.6` | `5` |
When needed, formatting rounds the displayed value. It does not change the original number.
Precision can also limit text. In the program, %.4s displays only the first four characters of "pearl", giving pear. This is a length limit, not a way to find whole words.
Set Width and Alignment
Width is the minimum space reserved for a formatted value. In the example, %8s reserves eight spaces for text. If the text is shorter, Java adds spaces on the left.
A flag is a symbol that changes how a placeholder works. The - flag moves the extra spaces to the right:
| Placeholder | Meaning | Result for `"tea"` |
|---|---|---|
| `[%8s]` | Pad on the left | `[ tea]` |
| `[%-8s]` | Pad on the right | `[tea ]` |
The square brackets are ordinary text. They make the spaces easier to see.
Width is a minimum, not a limit. If the value is longer than the width, Java displays the full value.
For whole numbers, the 0 flag adds leading zeroes. In the program, %05d reserves at least five positions, so 42 becomes 00042. A minus sign, when present, also takes up a position.
Reuse a Value
Sometimes the same value needs to appear more than once. An argument index is a number in a placeholder that selects which argument to use. Indexes in format strings start at 1.
The worked example uses this format string:
"First: %1$s; again: %1$s; count: %2$d"Both %1$s placeholders use the first value, name. The %2$d placeholder uses the second value, count.
Using indexes is helpful when a value appears several times. If you use indexes, use them consistently for the values in that format string.
Choose a Locale
A locale is a set of settings for a language or region. It can affect how formatted numbers appear.
The example formats the same number with two locales:
Locale.USproduces12,345.50.Locale.GERMANYproduces12.345,50.
The comma flag in %,.2f asks Java to group large numbers. The locale decides which marks to use for grouping and for the decimal point.
If you do not supply a locale, Java uses the program’s default locale. That can differ between computers. Supply a locale when you need a predictable result, such as text in a file that another program will read.
For prices shown to users in different regions, a fixed dollar sign and %.2f may not be enough. Java also provides NumberFormat for locale-aware currency display.
Common Mistakes
Using the wrong type
Each placeholder expects a suitable kind of value. Use %d for a whole number and %f for a floating-point number.
For example, a double value such as 4.5 does not work with %d. Java throws an exception, which is an error reported while the program runs. Choose %.2f instead if you want to display 4.50.
Likewise, %f expects a floating-point value. An integer argument such as 4 is not the same type as 4.0.
Forgetting an argument
Each ordinary placeholder needs a matching argument. If the format string has two placeholders but you provide only one value, formatting fails with an exception.
The special placeholders %% and %n do not need arguments.
Forgetting to escape a percent sign
A percent sign starts a placeholder. To show a percent sign as text, write %%. In the worked example, %d%% uses one value for %d and then displays %.
Expecting a line break
System.out.printf prints exactly what the format string asks for. Add %n when you want a line break. Unlike a fixed line-break character, %n uses the line break for the system running the program.
Treating missing text as empty text
The %s placeholder can display null, but it shows the word null, not an empty space. Decide how your program should handle missing values before formatting them.
Exercises
Exercise
With Locale.US, what string does String.format("[% -6s]", "tea") produce?
Show answer
It throws an exception because the space flag is not allowed with %s. Use "[%-6s]" to produce "[tea ]".
Exercise
With Locale.US, what is the result of String.format("[%-6s][%05d][%.2f%%]", "tea", 7, 12.5)?
Show answer
"[tea ][00007][12.50%]"