31

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".

Peter
  • 837
  • 3
  • 14
  • 19

10 Answers10

23

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", "");
G__
  • 7,003
  • 5
  • 36
  • 54
Bradley Swain
  • 804
  • 5
  • 12
  • 2
    'currencyString.replaceAll( regexp, String)' is inefficient in this case. 'currencyString = currencyString.replace( ".00", "" );' is much more efficient. replaceAll requires compiling a Pattern, creating a Matcher, etc. This can be quite costly, especially if the code is executing in a display loop on Mobile devices with limited resources (Android). – Frank Harper Aug 02 '13 at 09:07
  • Worth noting that `NumberFormat.getCurrencyInstance()` will only format with $ if your `Locale` is set to US. To specify the currency explicitly you can pass a `Locale` - for example `NumberFormat.getCurrencyInstance(Locale.US)` here – davnicwil Feb 15 '14 at 22:56
9

Use NumberFormat:

NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
double doublePayment = 100.13;
String s = n.format(doublePayment);
System.out.println(s);

Also, don't use doubles to represent exact values. If you're using currency values in something like a Monte Carlo method (where the values aren't exact anyways), double is preferred.

See also: Write Java programs to calculate and format currency

6

Try

new DecimalFormat("'$'0.00");

Edit:

I Tried

DecimalFormat d = new DecimalFormat("'$'0.00");

        System.out.println(d.format(100));
        System.out.println(d.format(100.5));
        System.out.println(d.format(100.41));

and got

$100.00
$100.50
$100.41
Bala R
  • 107,317
  • 23
  • 199
  • 210
3

Try using

DecimalFormat.setMinimumFractionDigits(2);
DecimalFormat.setMaximumFractionDigits(2);
Rafael T
  • 15,401
  • 15
  • 83
  • 144
  • it does! `code`public class Testing { /** * @param args */ public static void main(String[] args) { double d = 100.5; DecimalFormat df = new DecimalFormat("'$'0.##"); df.setMaximumFractionDigits(2); df.setMinimumFractionDigits(2); String currency = df.format(d); System.out.println(currency); } } `code` – Rafael T Feb 17 '11 at 19:26
  • @Peter, did you mean case #1? That's where this doesn't seem to work (Java 1.6.0_22 on a mac), producing "$100.00" instead of "$100" which is what OP wanted. – Jonik Feb 17 '11 at 19:39
  • 1
    @Jonik yes exactly, sorry for the mistype. I've basically determined this is not possible using DecimalFormat and have moved onto other means to solve this problem. Thanks! – Peter Feb 17 '11 at 19:43
  • Ok Youre right You can try to 'hack' it for case #1 if you test `code`if(currency.substring(currency.indexOf(".")).equals("00")) { currency = currency.substring(0,currency.indexOf(".")) } `code` – Rafael T Feb 17 '11 at 19:48
1

You can check "is number whole or not" and choose needed number format.

public class test {

  public static void main(String[] args){
    System.out.println(function(100d));
    System.out.println(function(100.5d));
    System.out.println(function(100.42d));
  }

  public static String function(Double doubleValue){
    boolean isWholeNumber=(doubleValue == Math.round(doubleValue));
    DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.GERMAN);
    formatSymbols.setDecimalSeparator('.');

    String pattern= isWholeNumber ? "#.##" : "#.00";    
    DecimalFormat df = new DecimalFormat(pattern, formatSymbols);
    return df.format(doubleValue);
  }
}

will give exactly what you want:

100
100.50
100.42
ashakirov
  • 12,112
  • 6
  • 40
  • 40
1

You can use the following format:

DecimalFormat dformat = new DecimalFormat("$#.##");

mizanurahma
  • 139
  • 5
1

I know its too late. However following worked for me :

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.UK);
new DecimalFormat("\u00A4#######0.00",otherSymbols).format(totalSale);

 \u00A4 : acts as a placeholder for currency symbol
 #######0.00 : acts as a placeholder pattern for actual number with 2 decimal 
 places precision.   

Hope this helps whoever reads this in future :)

Shailesh Vaishampayan
  • 1,766
  • 5
  • 24
  • 52
1

You can try by using two different DecimalFormat objects based on the condition as follows:

double d=100;
double d2=100.5;
double d3=100.41;

DecimalFormat df=new DecimalFormat("'$'0.00");

if(d%1==0){ // this is to check a whole number
    DecimalFormat df2=new DecimalFormat("'$'");
    System.out.println(df2.format(d));
}

System.out.println(df.format(d2));
System.out.println(df.format(d3));

Output:-
$100
$100.50
$100.41
Andre Hofmeister
  • 3,185
  • 11
  • 51
  • 74
Sai Gattu
  • 11
  • 2
1

You could use the Java Money API to achieve this. (although this is not using DecialFormat)

long amountInCents = ...;
double amountInEuro = amountInCents / 100.00;

String customPattern; 
if (minimumOrderValueInCents % 100 == 0) {
    customPattern = "# ¤";
} else {
    customPattern = "#.## ¤";
}

Money minDeliveryAmount = Money.of(amountInEuro, "EUR");
MonetaryAmountFormat formatter = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder.of(Locale.GERMANY)
            .set(CurrencyStyle.SYMBOL)
            .set("pattern", customPattern)
            .build());

System.out.println(minDeliveryAmount);
Sebastian Thees
  • 3,113
  • 4
  • 14
  • 23
-1

printf also works.

Example:

double anyNumber = 100; printf("The value is %4.2f ", anyNumber);

Output:

The value is 100.00

4.2 means force the number to have two digits after the decimal. The 4 controls how many digits to the right of the decimal.

Casper
  • 3,765
  • 2
  • 13
  • 12