Java提供了printf()和format()输出带有格式化数字的输出的方法。String类具有等效的类方法,format()该方法返回String对象而不是PrintStream对象。
使用String的静态format()方法使您可以创建可重复使用的格式化字符串,而不是一次性的打印语句。例如,代替-
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);你可以写-
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);下面的示例通过在format()方法中使用特定的语言环境,格式和参数返回格式化的字符串值。
public class HelloWorld {
public static void main(String []args) {
String name = "Hello World";
String s1 = String.format("name %s", name);
String s2 = String.format("value %f",32.33434);
String s3 = String.format("value %32.12f",32.33434);
System.out.print(s1);
System.out.print("\n");
System.out.print(s2);
System.out.print("\n");
System.out.print(s3);
System.out.print("\n");
}
}输出结果
name Hello World value 32.334340 value 32.334340000000