Wednesday, November 7, 2007

Format Specifiers

Format Specifiers:

% [argument number] [flags] [width] [.precision] type

%: says, ‘insert arument here’ and format it using these instructions.

flags: these are for special formatting options like inserting commas, or
Putting negative numbers in parentheses, or to make the numbers
Left justified

width: This defines the Minimum number of characters that will be sued.
That’s minimum not TOTAL. If the number is longer than the width,it’ll still be used in
full, but if it’s less than the width, it’ll be padded with zeroes. Most of the time
this does not need to be specified.


.precision:  It defines the precision. In other words, it sets the number of decimal places.

type: Type is mandatory and will usually be ‘d’ for a decimal integer or ‘f’ for a floating
point number.

E.g. :
format(“%,3.1f”, 91.0000000); -> 91.0

complete example code:

public class FormatTest {

static String x = "";
static double y = 91.000000;

public static void main(String[] args) {

 x = String.format("%,3.1f", y);
 System.out.println(x);

}

} // produces: 42.0

// Adopted from HFJ

No comments:

Just some daily notes ...

Powered By Blogger