The output is shown here:
-100
100
-200
200
Notice that the positive values have a leading space, which causes the digits in the column
to line up properly.
To show negative numeric output inside parentheses, rather than with a leading –, use
the(flag. For example,
fmt.format("%(d", -100);
creates this string:
(100)
The 0 flag causes output to be padded with zeros rather than spaces.
The Comma Flag
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,
fmt.format("%,.2f", 4356783497.34);
creates this string:
4,356,783,497.34
The # Flag
The#can be applied to%o,%x,%e, and%f. For%eand%f, the#ensures that there
will be a decimal point even if there are no decimal digits. If you precede the%xformat
specifier with a#, the hexadecimal number will be printed with a0xprefix. Preceding the
%ospecifier with#causes the number to be printed with a leading zero.
The Uppercase Option
As mentioned earlier, several of the format specifiers have uppercase versions that cause the
conversion to use uppercase where appropriate. The following table describes the effect.
Specifier Effect
%A Causes the hexadecimal digitsathroughfto be displayed in uppercase asA
throughF.Also, the prefix0xis displayed as0X, and thepwill be displayed asP.
%B Uppercases the valuestrueandfalse.
Chapter 18: java.util Part 2: More Utility Classes 537