1

我在大学接受了 Java 的作业,我必须使用它printf来格式化输出到控制台。这一切都很好而且花花公子,但由于某种原因我得到了输出10500.000000000002,正确的输出应该是10500.00。我尝试使用%0.2f,但因为我格式化为 aString我不能这样做。

这是有问题的行:

System.out.printf("\nAge Depreciation Amount:%66s","$"+ ageDepreciationAmount);

你能建议一种正确格式化的方法吗?请记住,这是一门 Java 入门课程,这意味着我在编程方面完全是个灾难。

4

2 回答 2

2
DecimalFormat df = new DecimalFormat("0.##");
String result = df.format(10500.000000000002);
于 2013-03-23T16:07:35.613 回答
1

%0.2f是不正确的。你应该使用%.2f

例子:

System.out.printf("Age Depreciation Amount: %.2f\n", ageDepreciationAmount);

或者如果ageDepreciationAmountString

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
于 2013-03-23T16:12:31.160 回答