Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

530 Part II: The Java Library


It produces the following output:

1000.000000
1000.000000 100000.000000
1000.000000 100000.000000 1.000000e+07
1000.000000 100000.000000 1.000000e+07 1.000000e+09

You can display integers in octal or hexadecimal format by using%oand%x, respectively.
For example, this fragment:

fmt.format("Hex: %x, Octal: %o", 196, 196);

produces this output:

Hex: c4, Octal: 304

You can display floating-point values in hexadecimal format by using%a. The format
produced by%aappears a bit strange at first glance. This is because its representation uses
a form similar to scientific notation that consists of a significand and an exponent, both in
hexadecimal. Here is the general format:

0x1.sigpexp

Here,sigcontains the fractional portion of the significand andexpcontains the exponent.
Thepindicates the start of the exponent. For example, this call:

fmt.format("%a", 123.123);

produces this output:

0x1.ec7df3b645a1dp6

Formatting Time and Date


One of the more powerful conversion specifiers is%t. It lets you format time and date
information. The%tspecifier works a bit differently than the others because it requires the
use of a suffix to describe the portion and precise format of the time or date desired. The
suffixes are shown in Table 18-13. For example, to display minutes, you would use%tM,
whereMindicates minutes in a two-character field. The argument corresponding to the%t
specifier must be of typeCalendar,Date,Long, orlong.
Here is a program that demonstrates several of the formats:

// Formatting time and date.
import java.util.*;

class TimeDateFormat {
public static void main(String args[]) {
Formatter fmt = new Formatter();
Calendar cal = Calendar.getInstance();
Free download pdf