Java Reference
In-Depth Information
Using Flags in a Format Specifier
Flags act as modifiers. They modify the formatted output. Table 13-3 lists all flags that can be used in a format specifier.
Table 13-3. List of Valid Flags, Their Descriptions, and Examples of Their Usage
Flag
Description
Examples
Format String
Argument
Formatted Text
'-'
The result is left justified. Note that
the result is right justified when you do
not use the '-' flag in a format specifier.
“'%6s'”
“Ken”
' Ken'
“'%-6s'”
“Ken”
'Ken '
'#'
The argument is formatted in alternate
form depending on the conversion part
of the format specifier. The example
shows the same decimal number, 6270185,
being formatted to a hexadecimal format.
When '#' flag is used, the hexadecimal number
is prefixed with “0x”.
“%x”
6270185
5face9
“%#x”
6270185
0x5face9
'+'
The result contains a + sign for positive
values. It applies only to numeric values.
“%d”
105
105
“%+d”
105
+105
' '
The result contains a leading space
for positive values. It applies only to
numeric values.
“'%d'”
105
'105'
“'% d'”
105
' 105'
'0'
The result is zero padded. It applies
only to numeric values.
“'%6d'”
105
' 105'
“'%06d'”
105
'000105'
' , '
The result contains a locale-specific
grouping separator. It applied only to
numeric values. For example, a comma is
used as a thousand-separator in US locale,
whereas a space is used in France locale.
“%,d”
89105
89,105 (US Locale)
“%,d”
89105
89 105 (France locale)
'('
The result is enclosed in
parentheses for a negative number.
It applies only to numeric values.
“%d”
-1969
-1969
“%(d”
-1969
(1969)
'<'
It causes the argument for the previous
format specifier to be reused. It is mostly
used in formatting dates and times.
“%s and %<s”
“Ken”
Ken and Ken
The valid use of a flag depends on the context of its use. Depending on the value being formatted, it is allowed to
use multiple flags in a format specifier. For example, the format specifier "%1$,0(12d" uses three flags: ',' , '0' , and
'(' . If -122899 is used as the argument by this format specifier, it will output (000122,899) . The effects of using each
flag will be discussed in detail when I discuss formatting for different data types in the sections to follow.
 
 
Search WWH ::




Custom Search