Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

536 Part II: The Java Library


fmt.format("|%-10.2f|", 123.123);
System.out.println(fmt);
}
}

It produces the following output:

| 123.12|
|123.12 |

As you can see, the second line is left-justified within a 10-character field.

The Space, +, 0, and ( Flags


To cause a+sign to be shown before positive numeric values, add the+flag. For example,

fmt.format("%+d", 100);

creates this string:

+100

When creating columns of numbers, it is sometimes useful to output a space before
positive values so that positive and negative values line up. To do this, add the space flag.
For example,

// Demonstrate the space format specifiers.
import java.util.*;

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

fmt.format("% d", -100);
System.out.println(fmt);

fmt = new Formatter();
fmt.format("% d", 100);
System.out.println(fmt);

fmt = new Formatter();
fmt.format("% d", -200);
System.out.println(fmt);

fmt = new Formatter();
fmt.format("% d", 200);
System.out.println(fmt);
}
}
Free download pdf