Java Tutorial/Development/Formatter Field Width — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 15:30, 31 мая 2010
Содержание
- 1 Displaying at most 15 characters in a string
- 2 Format to 2 decimal places in a 16-character field
- 3 Limit the number of decimal digits by specifying the precision
- 4 Specifying a Minimum Field Width
- 5 The minimum field width specifier by applying it to the %f conversion
- 6 To produce tables with the columns lining up
Displaying at most 15 characters in a string
import java.util.Formatter;
public class MainClass {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt = new Formatter();
fmt.format("%.15s", "Formatting with Java is now easy.");
System.out.println(fmt);
}
}
Formatting with
Format to 2 decimal places in a 16-character field
import java.util.Formatter;
public class MainClass {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt = new Formatter();
fmt.format("%16.2e", 123.1234567);
System.out.println(fmt);
}
}
1.23e+02
Limit the number of decimal digits by specifying the precision
import java.util.Formatter;
public class Main {
public static void main(String[] argv) throws Exception {
Formatter fmt = new Formatter();
fmt.format("Default precision: %f\n", 10.0 / 3.0);
fmt.format("Two decimal digits: %.2f\n\n", 10.0 / 3.0);
System.out.println(fmt);
}
}
Specifying a Minimum Field Width
An integer between the % sign and the format conversion code acts as a minimum field width specifier.
The default padding is done with spaces.
If you want to pad with 0"s, place a 0 before the field width specifier.
For example, %05d will pad a number of less than five digits with 0"s.
import java.util.Formatter;
public class MainClass {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt.format("%05d", 88);
System.out.println(fmt);
}
}
00088
The minimum field width specifier by applying it to the %f conversion
import java.util.Formatter;
public class MainClass {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt.format("|%f|%n|%12f|%n|%012f|", 10.12345, 10.12345, 10.12345);
System.out.println(fmt);
}
}
|10.123450| | 10.123450| |00010.123450|
To produce tables with the columns lining up
import java.util.Formatter;
public class MainClass {
public static void main(String args[]) {
Formatter fmt;
for(int i=1; i <= 10; i++) {
fmt = new Formatter();
fmt.format("%4d %4d %4d", i, i*i, i*i*i);
System.out.println(fmt);
}
}
}
1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000