Java Reference
In-Depth Information
// Each format code consists of the following:
// % - code lead-in
// N$ - which parameter number (1-based) after the code - OPTIONAL
// N - field width
// L - format letter (d: decimal(int); f: float; s: general; many more)
// For the full(!) story, see javadoc for java.util.Formatter.
// Most general (cumbersome) way of proceding.
Formatter fmtr = new
new Formatter ();
Object result = fmtr . format ( "%1$04d - the year of %2$f" , 1956 , Math . PI );
System . out . println ( result );
// Shorter way using static String.format(), and
// default parameter numbering.
Object stringResult = String . format ( "%04d - the year of %f" , 1956 , Math . PI );
System . out . println ( stringResult );
// A shorter way using PrintStream/PrintWriter.format, more in line with
// other languages. But this way you must provide the newline delimiter
// using %n (do NOT use \n as that is platform-dependent!).
System . out . printf ( "%04d - the year of %f%n" , 1956 , Math . PI );
// Format doubles with more control
System . out . printf ( "PI is approximately %4.2f%n" , Math . PI );
}
}
Running FormatterDemo produces this:
C:> javac FormatterDates.java
C:> java io.FormatterDates
1956 - The year of 3.141593
1956 - The year of 3.141593
1956 - The year of 3.141593
PI is about 3.14
For formatting legacy java.util date and time objects, a large variety of format codes are
available—about 40 in all. For formatting java.time date and time objects, a similarly large
API is available, discussed in Chapter 6 .
Table 10-2 shows the more common date/time format codes. Each must be preceded by a t ,
so to format the first argument as a year, you would use %1$tY .
Search WWH ::




Custom Search