See API for java.util.Formatter...
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html In general, a
format string (the first argument to String.format) for
numeric material has the syntax:
%[argument_index$][flags][width][.precision]conversion
The bracketed components are all optional, so at a minimum we need the percent sign followed by the appropriate conversion character. In this case, we're dealing with floating point numbers, so we probably want a conversion character of f. Therefore, our format string is at least "%f".
Now, let's customize using the optional components...
First, we'll want each of these to show 2 digits to the right of the decimal, so we'll add the [.precision] component. (Note the decimal point that flags this as a precision indicator.) Basically, this inserts trailing zeros or rounds as needed. So inserting ".2" gives us a format string of "%.2f".
Now, we also want to align on the decimal. We've already ensured that there are exactly two digits to the right of the decimal, so what we really want is to right-justify within a column. To do this, we only need to specify a maximum width using the [width] component, because the default is to right-justify
within that width. Twelve spaces should ensure ample room for illustration purposes, so inserting a width component of "12" gives us a format string of "%12.2f".
Finally, we'll add a flag component to include a locale-specific grouping separator (e.g., a comma separating thousands). This gives us a format string of "%,12.2f".
The following code demonstrates the result, using an array of doubles as
test data...
Note that each output String is 12 characters wide, with leading spaces inserted so that the number is right-justified within this width. The number itself has been rounded to 2 decimal places (with trailing zeros as needed) and is displayed with a comma separator (as needed).
(Also note the new
printf method in PrintStream, which could further streamline the above code.)
[ February 09, 2005: Message edited by: marc weber ]