Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java printf标志显示不正确?_Java_Printf - Fatal编程技术网

Java printf标志显示不正确?

Java printf标志显示不正确?,java,printf,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

我的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 
为什么“$”会向左移动这么多字符,而它应该位于我的每个值的开头?

因为

"%10d $%10.2f 
表示一个数字最多使用10个字符(数字位于10列的右侧)

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

然后,对另一个小数点后有2位数字的数字再使用10个字符,然后将该数字向右推

如果你想要数字旁边的美元符号,你必须使用

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.

还有其他方法。

当格式为:
%10.2f
时,您指定了总长度为
10
,并且您的
$
字符在格式化数字之前。所以你有

"$" + "      5.00"
您可以使用
DecimalFormat
解决此问题:

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

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

     $5.00