Conversions and Java Print Streams - Flags
(Page 4 of 5 )
Flags indicate a variety of formatting options. Not all flags apply to all types. Using a flag to format a type that does not apply throws a FormatFlagsConversionMismatchException, a subclass of IllegalFormatException. However, you can combine multiple flags that do apply. Table 7-1 summarizes these flags.
Table 7-1. Format flags
| Flag | Signifies | Applies to |
|---|
| - | Left-justify. | All |
| # | Alternate form. | General, integer, floating point |
| + | Include a sign even if positive. (Normally, only negative numbers have signs.) | Integer, floating point |
| space | Add a leading space to positive numbers. (This is where the sign would be and helps line up positive and negative numbers.) | Integer, floating point |
| 0 | Pad with zeros instead of spaces. | Integer, floating point |
| , | Use the locale-specific grouping separator instead of a period. | Integer, floating point |
| ( | Use instead of a minus sign to indicate negative numbers. | Integer, floating point |
For example, this statement prints adoubleformatted as a 20-character decimal padded with zeros, using a locale-specific grouping separator and parentheses for negative numbers:
System.out.printf("%(+0,20f", -Math.PI);
The result is(00000000003.141593).
The relative order of the flags does not matter. This statement prints the same thing:
System.out.printf("%,0+(20f", -Math.PI);
Width
Each of the various conversions may be preceded by an optional width. This sets the minimum number of characters to print. For example, if you format an integer using the code %5d, it will always be printed at least five characters wide. If the integer has fewer than five digits, extra spaces are added on the left-hand side to make up five characters. If it has five or more digits, no extra spaces are added.
The entire number is always printed. If the argument is larger than can fit in five places, all of it will be printed anyway, and subsequent columns may no longer line up properly.
For example, this statement prints five mathematical constants, each 12 places wide:
System.out.printf("%12f %12f %12f %12f
%12f",
Math.PI, Math.E, 1.0, 0.0, Math.sqrt(2));
By default, extra places are filled with space characters to right-justify the numbers. However, flags can be used to fill extra places with zeros or to left-justify the numbers instead.
This is the output:
3.141593 2.718282 1.000000 0.000000 1.414214
Width is not limited to numeric types. You can specify a width for any format tag: date, time, boolean, and so on.
Next: Precision >>
More Java Articles
More By O'Reilly Media
|
This article is excerpted from chapter seven of Java I/O, Second Edition, written by Elliotte Rusty Harold (O'Reilly, 2006; ISBN: 0596527500). Check it out today at your favorite bookstore. Buy this book now.
|
|