I'd like to use Java's DecimalFormat to format doubles like so:
#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41
The best I can come up with so far is:
new DecimalFormat("'$'0.##");
But this doesn't work for case #2, and instead outputs "$100.5"
Edit:
A lot of these answers are only considering cases #2 and #3 and not realizing that their solution will cause #1 to format 100 as "$100.00" instead of just "$100".
Does it have to use DecimalFormat
?
If not, it looks like the following should work:
String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
//Handle the weird exception of formatting whole dollar amounts with no decimal
currencyString = currencyString.replaceAll("\\.00", "");