%0.2f
是不正确的。你应该使用%.2f
:
例子:
System.out.printf("Age Depreciation Amount: %.2f\n", ageDepreciationAmount);
或者如果ageDepreciationAmount
是String
做
System.out.printf("Age Depreciation Amount: %.2f\n", Double.parseDouble(ageDepreciationAmount));
顺便说一句,我们通常\n
在 printf 之后添加,而不是之前。
输出:
Age Depreciation Amount: 10500.00
如果您想用空格填充输出,您可以使用%66.2
,其中66
是总宽度,并且2
是小数位数。但是,这只适用于数字。由于您还需要打印美元符号,您可以分两步完成,如下所示:
double ageDepreciationAmount = 10500.000000000002;
double ageDepreciationAmount2 = 100500.000000000002;
String tmp = String.format("$%.2f", ageDepreciationAmount);
String tmp2 = String.format("$%.2f", ageDepreciationAmount2);
System.out.printf("Age Depreciation Amount: %20s\n", tmp);
System.out.printf("Age Depreciation Amount: %20s\n", tmp2);
输出:
Age Depreciation Amount: $10500.00
Age Depreciation Amount: $100500.00