Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 18: java.util Part 2: More Utility Classes 535


fmt.format("%.15s", "Formatting with Java is now easy.");
System.out.println(fmt);
}
}


It produces the following output:


123.1235
1.23e+02
Formatting with

Using the Format Flags


Formatterrecognizes a set of formatflagsthat lets you control various aspects of a conversion.
All format flags are single characters, and a format flag follows the%in a format specification.
The flags are shown here:


Flag Effect


  • Left justification

    Alternate conversion format


    0 Output is padded with zeros rather than spaces
    space Positive numeric output is preceded by a space





  • Positive numeric output is preceded by a + sign
    , Numeric values include grouping separators
    ( Negative numeric values are enclosed within parentheses


Not all flags apply to all format specifiers. The following sections explain each in detail.


Justifying Output


By default, all output is right-justified. That is, if the field width is larger than the data printed,
the data will be placed on the right edge of the field. You can force output to be left-justified
by placing a minus sign directly after the %. For instance,%–10.2fleft-justifies a floating-point
number with two decimal places in a 10-character field. For example, consider this program:


// Demonstrate left justification.
import java.util.*;


class LeftJustify {
public static void main(String args[]) {
Formatter fmt = new Formatter();


// Right justify by default
fmt.format("|%10.2f|", 123.123);
System.out.println(fmt);

// Now, left justify.
fmt = new Formatter();
Free download pdf