Java格式修饰符在字符串中加倍
我在Java大学接受了一项作业,在那里我必须使用Java格式修饰符在字符串中加倍,java,printf,formatting,Java,Printf,Formatting,我在Java大学接受了一项作业,在那里我必须使用printf格式化控制台的输出。这一切都很好,但出于某种原因,我得到了输出10500.000000000002,正确的输出应该是10500.00。我试图使用%0.2f,但因为我使用字符串格式化,所以无法使用 这就是问题所在: System.out.printf("\nAge Depreciation Amount:%66s","$"+ ageDepreciationAmount); 你能建议一种正确格式化的方法吗?请记住,这是一门java入门课程
printf
格式化控制台的输出。这一切都很好,但出于某种原因,我得到了输出10500.000000000002
,正确的输出应该是10500.00
。我试图使用%0.2f
,但因为我使用字符串格式化,所以无法使用
这就是问题所在:
System.out.printf("\nAge Depreciation Amount:%66s","$"+ ageDepreciationAmount);
你能建议一种正确格式化的方法吗?请记住,这是一门java入门课程,这意味着在编程方面我是一个彻底的灾难。%0.2f
是不正确的。您应该使用%.2f
:
DecimalFormat df = new DecimalFormat("0.##");
String result = df.format(10500.000000000002);
例如:
System.out.printf("Age Depreciation Amount: %.2f\n", ageDepreciationAmount);
或者如果agedecivalionamount
是字符串
do
System.out.printf("Age Depreciation Amount: %.2f\n", Double.parseDouble(ageDepreciationAmount));
顺便说一句,我们通常在printf之后而不是之前添加\n
输出:
Age Depreciation Amount: 10500.00
Age Depreciation Amount: $10500.00
Age Depreciation Amount: $100500.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: $10500.00
Age Depreciation Amount: $100500.00
说到编程xDOK,我是一个彻底的灾难。谢谢你的工作,但是现在我如何将10500.00移到右边一定的空间。在我前面的示例中,它将年限折旧金额后的输出向右移动66个空格,然后输出美元符号和105000.00。所以它看起来像年限折旧额uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu$10500.00