Format Flags
Formatter recognizes a set of format flags that lets you control various aspects of a conversion. All format flags are single characters, and a format flag follows the % in a format specification. Some of those:
Left justification
By default, all output is right-justified. That is, if the field width is larger than the data printed, the data will be placed on the right edge of the field. You can force output to be left-justified by placing a minus sign directly after the %. For instance, %–8d left-justifies a decimal number in a 8-character field. For example:
The second line is left-justified within a 8-character field.
The +, 0, ( and Comma Flags
To cause a + sign to be shown before positive numeric values, add the + flag. To show negative numeric output inside parentheses, rather than with a leading –, use the ( flag. The 0 flag causes output to be padded with zeros rather than spaces. When displaying large numbers, it is often useful to add grouping separators, which in English are commas. For example, the value 1234567 is more easily read when formatted as 1,234,567. To add grouping specifiers, use the comma (,) flag. For example:
Program
Program Source
import java.util.Formatter; public class Javaapp { public static void main(String[] args) { Formatter fmt = new Formatter(); fmt.format("[%8d]",1234); fmt.format("%n[%-8d]",1234); fmt.format("%n%+d",1234); fmt.format("%n%d",-1234); fmt.format("%n%(d",-1234); fmt.format("%n[%08d]",1234); fmt.format("%n%,d",123456789); System.out.println(fmt); } }