Reputation: 3327
I have in my function the following statement System.out.printf("The balance is %0.1f", acct.getBalance());
, sometimes the balance will be 0, when this is the case, I get MissingFormatWidthException
, how can I make this work even for 0.0
? It works perfectly for doubles greater than 0.0.
Upvotes: 1
Views: 2911
Reputation: 49372
System.out.printf("The balance is %.1f",(double)acct.getBalance());
OR
System.out.printf("The balance is %1.1f",(double)acct.getBalance());
%0.1f
interprets as print as a floating point at least 0 wide and a precision of 2. It should ideally give errors.
Upvotes: 4
Reputation: 2753
Try this:
System.out.printf("The balance is %0.1f", acct.getBalance() !=0 ? acct.getBalance() : 0.0);
Upvotes: 1
Reputation: 2079
try this :
NumberFormat f = NumberFormat.getCurrencyInstance();
f.setMinimumFractionDigits(2);
double d = 0.0;
System.out.println(f.format(d));
Output:
$0.00
Upvotes: 1