Java在printf中打印double值为零

时间:2013-04-23 12:27:54

标签: java double printf string-formatting

我在我的函数中有以下语句System.out.printf("The balance is %0.1f", acct.getBalance());,有时余额将为0,在这种情况下,我得到MissingFormatWidthException,我怎样才能使0.0工作}?它适用于大于0.0的双精度。

3 个答案:

答案 0 :(得分:4)

System.out.printf("The balance is %.1f",(double)acct.getBalance());

OR

System.out.printf("The balance is %1.1f",(double)acct.getBalance());

%0.1f将打印解释为浮点数至少为0且精度为2.理想情况下应该给出错误。

答案 1 :(得分:1)

试试这个:

 NumberFormat f = NumberFormat.getCurrencyInstance();
 f.setMinimumFractionDigits(2);
 double d = 0.0;
 System.out.println(f.format(d));

输出:

 $0.00

答案 2 :(得分:1)

试试这个:

System.out.printf(“余额为%0.1f”,acct.getBalance()!= 0?acct.getBalance():0.0);