system.out.format("pi is approximately %f", math.pi); system.out.printf("pi is approximately %f", math.pi); format( string format, object... args); printf( string format, object... args); format( locale locale, string format, object... args); printf( locale locale, string format, object... args); |
同时,以前的formatter类也提供了更完善的方法来格式化,例如:
formatter.format("pi is approximately %1$f," + "and e is about %2$f", math.pi, math.e); |
格式化元素的构成如下:
%[argument_index$][flags][width][.precision]conversion 其中: argument_index是一个正整数,说明了参数的位置,1为取第一个参数 width表示输出的最小字母个数 precision代表数字的小数位数 conversion代表被格式化的参数的类型:
|
以下是个例子:
package format; import java.util.formatter; public class usingformatter { public static void main(string[] args) { if (args.length != 1) { system.err.println("usage: " + "java format/usingformatter "); system.exit(0); } string format = args[0]; stringbuilder stringbuilder = new stringbuilder(); formatter formatter = new formatter(stringbuilder); formatter.format("pi is approximately " + format + ", and e is about " + format, math.pi, math.e); system.out.println(stringbuilder); } } //控制台调用 java format/usingformatter %f //输出 pi is approximately 3.141593, and e is about 2.718282 //控制台调用 java format/usingformatter %.2f //输出 pi is approximately 3.14, and e is about 2.72 //控制台调用 java format/usingformatter %6.2f //输出(有空格来填补长度) pi is approximately 3.14, and e is about 2.72 //控制台调用 java format/usingformatter
pi is approximately 3.14, and e is about 3.14 //改变区域设置 package format; import java.util.formatter; import java.util.locale; public class usingformatter { public static void main(string[] args) { if (args.length != 1) { system.err.println("usage: " + "java format/usingformatter <format string>"); system.exit(0); } string format = args[0]; stringbuilder stringbuilder = new stringbuilder(); formatter formatter = new formatter(stringbuilder, locale.france); formatter.format("pi is approximately " + format + ", and e is about " + format, math.pi, math.e); system.out.println(stringbuilder); } } //控制台调用 java format/usingformatter %.2f //输出 pi is approximately 3,14, and e is about 2,72 //采用format,printf的可替代写法 package format; public class usingsystemout { public static void main(string[] args) { if (args.length != 1) { system.err.println("usage: " + "java format/usingsystemout <format string>"); system.exit(0); } string format = args[0]; system.out.format("pi is approximately " + format + ", and e is approximately " + format, math.pi, math.e); } } //控制台调用 java format/usingsystemout %.2f%n //输出 pi is approximately 3.14 , and e is about 2.72 |
对时间的格式化用字母t来代表,通常在t后面加上特殊的字符来显示时间的某个部分:
tr hour and minute,
//eg. package format; import java.util.calendar; public class formattingdates { public static void main(string[] args) { system.out.printf("right now it is %tr on " + "%<ta, %<tb %<te, %<ty.%n", calendar.getinstance()); } } //说明:“<”指示采用的参数为前一个被格式化的参数 //输出 right now it is 01:55:19 pm on wednesday, september 22, 2004. |