printf标志显示不正确?

时间:2013-10-11 20:06:38

标签: java printf

我的AP书中说,如果你把“$”放在%之前,它会输出前面带有“$”的任何值,这从我所理解的被称为标志。然而,当我这样做时,我得到了不同的东西,例如:

public void printResults(){
    System.out.printf("%10s %10s %10s \n", "Item:", "Cost:", "Price:");
    System.out.printf("%10d $%10.2f %10.2f \n", n++ ,productOne, productOne);
    System.out.printf("%10d $%10.2f %10.2f \n", n++ ,productTwo, productTwo+=productOne);
    System.out.printf("%10d $%10.2f %10.2f", n++ ,productThree, productThree+=productTwo);
}

这输出:

 Item:      Cost:     Price: 
     1 $      5.00       5.00 
     2 $      5.00      10.00 
     3 $      5.00      15.00

而不是:

 Item:      Cost:     Price: 
     1       $5.00       5.00 
     2       $5.00      10.00 
     3       $5.00      15.00 

为什么“$”会出现在左边那么多字符,因为它应该是在我的每个值的开头?

2 个答案:

答案 0 :(得分:0)

因为这个

"%10d $%10.2f 

表示使用10个字符作为数字(10列右侧的数字)

然后放一个空格和一个美元符号

然后再用10个字符代表另一个数字,小数点后2位数字,数字向右推。

如果您希望数字旁边有美元符号,则必须使用

String one = NumberFormat.getCurrencyInstance().format(productOne);
System.out.printf("%10d %11s %10.2f \n", n++ ,one, productOne);

或以其他方式格式化数字,例如

String one = "$" + productOne; // this won't do exactly 2 fractional digits.

还有其他方法。

答案 1 :(得分:0)

当您的格式显示为10时,您指定的总长度为%10.2f,并且您的$字符位于格式化的数字之前。所以你得到了

"$" + "      5.00"

您可以使用DecimalFormat来解决此问题:

DecimalFormat df = new DecimalFormat("$#.00");
String s = df.format(productOne);

以后

System.out.printf("%10s \n");

输出:

     $5.00
相关问题