Thursday, October 6, 2011

SCJP 6 Part IX - Formatting String with Formatter

Here is the format
%[arg_index$][flags][width][.precision]conversion_char

arg_index
An integer followed directly by a $, this indicates which argument should be printed in this position.

flags
"-" Left justify this argument
"+" Include a sign (+ or -) with this argument
"0" Pad this argument with zeroes
"," Use locale-specific grouping separators
"(" Enclose negative numbers in parentheses

width
This value indicates the minimum number of characters to print.

precision
When formatting a floating-point number, precision indicates the number of digits to print after the decimal point.

conversion_char
The type of argument we'll be formatting.
b boolean
c char
d integer
f floating point
s string

Formatter formatter = new Formatter(System.out);

// format int and use italian switzerland separator
formatter.format(new Locale("it", "ch"), "%,d", 1000000); // 1'000'000

// format int, use italian switzerland separator, and give parentheses for negative int
formatter.format(new Locale("it", "ch"), "%(,d", -1000000); // (1'000'000)

// format int, use italian switzerland separator, and put a sign on it
formatter.format(new Locale("it", "ch"), "%,+d", 1000000); // +1'000'000

0 comments:

 

©2009 Stay the Same | by TNB