108

Is there a way to format a decimal as following:

100   -> "100"  
100.1 -> "100.10"

If it is a round number, omit the decimal part. Otherwise format with two decimal places.

TylerH
  • 20,799
  • 66
  • 75
  • 101
DD.
  • 21,498
  • 52
  • 157
  • 246

22 Answers22

179

I'd recommend using the java.text package:

double money = 100.1;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String moneyString = formatter.format(money);
System.out.println(moneyString);

This has the added benefit of being locale specific.

But, if you must, truncate the String you get back if it's a whole dollar:

if (moneyString.endsWith(".00")) {
    int centsIndex = moneyString.lastIndexOf(".00");
    if (centsIndex != -1) {
        moneyString = moneyString.substring(1, centsIndex);
    }
}
daiscog
  • 11,441
  • 6
  • 50
  • 62
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 24
    You should never use a double to represent currencies. Either convert to longs and manage the decimal point yourself or use `BigDecimal` with a formatter. http://joda-money.sourceforge.net/ should be a nice library to use once it's done. – gpampara Mar 04 '10 at 14:44
  • 5
    I agree re: double != money, but that's not how the question was posed. – duffymo Mar 04 '10 at 14:56
  • 3
    What do you mean thats how currencies work? I can say something costs $1 not $1.00....there are different way of displaying currencies (other than the default) and this questions asks how to omit the decimal part if its a whole number. – DD. Dec 10 '12 at 23:08
  • 1
    It's a rendering issue. Put the logic in your UI to accept the currency as a String and truncate the decimal and cents if it's an exact dollar. – duffymo Dec 10 '12 at 23:28
  • Can I use the following: `if (!dolVal.endsWith(".##"))` to ensure if there is NO number or decimal to attach the 00? – Si8 Oct 11 '13 at 20:23
  • also for ints only http://developer.android.com/reference/java/text/NumberFormat.html#setParseIntegerOnly(boolean) – Dori Feb 24 '14 at 10:01
  • 1
    This solution won't work if the locale has the decimal separator as a comma. E.g Spain: €1.234,00 (1,234.00 in U.S. Format) – DD. Apr 25 '15 at 09:28
  • 1
    Have you tried it? The NumberFormatter is Locale-aware. It should know about your comma separator. – duffymo Apr 25 '15 at 11:15
  • @duffymo DD is right - if the string ends ",00" (note the comma) instead of ".00" then the lastIndexOf check won't work. It will also fail for locales which have the currency symbol after the number, like French (e.g., "1000,00 €"). – daiscog Sep 14 '15 at 13:50
  • 2
    Agreed - that's why I recommended using Locale when I wrote this 5.5 years ago. "But, if you must,...." is the key phrase. – duffymo Sep 14 '15 at 14:35
  • Why are you trimming the currency symbol only when it's a whole dollar? And why call `lastIndexOf()` altogether? Just get `moneyString.substring(1, moneyString.length() - 3)`. – shmosel Jan 11 '19 at 04:35
156
double amount =200.0;
Locale locale = new Locale("en", "US");      
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
System.out.println(currencyFormatter.format(amount));

or

double amount =200.0;
System.out.println(NumberFormat.getCurrencyInstance(new Locale("en", "US"))
        .format(amount));

The best way to display currency

Output

$200.00

Note: Locale constructors have been deprecated. See Obtaining a Locale for other options.

have

So, since Locale constructors are deprecated, we can use Locale.Builder() to construct a Locale object.

    double amount =200.0;
    Locale locale = new Locale.Builder().setLanguage("en").setRegion("US").build();
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
    System.out.println(currencyFormatter.format(amount));

or

    double amount =200.0;
    System.out.println(NumberFormat.getCurrencyInstance(new Locale.Builder().setLanguage("en").setRegion("US").build()).format(amount));

Output

$200.00

If you don't want to use sign use this method

double amount = 200;
DecimalFormat twoPlaces = new DecimalFormat("0.00");
System.out.println(twoPlaces.format(amount));

200.00

This also can be use (With the thousand separator )

double amount = 2000000;    
System.out.println(String.format("%,.2f", amount));          

2,000,000.00

Pain
  • 111
  • 1
  • 2
  • 12
Thilina Dharmasena
  • 2,243
  • 2
  • 19
  • 27
  • It doesn't look like "currency" is referenced or used after it is declared... is there a side effect of line 3? Or some reason you included it? – Damian Feb 18 '15 at 08:38
  • Read more about [Class Locale][1] [1]: http://docs.oracle.com/javase/7/docs/api/java/util/Locale.html#Locale%28java.lang.String,%20java.lang.String%29 – Thilina Dharmasena May 11 '15 at 13:18
  • fyi. Locale is Threadsafe, NumberFormat is not – muttonUp Sep 15 '22 at 09:59
50

I doubt it. The problem is that 100 is never 100 if it's a float, it's normally 99.9999999999 or 100.0000001 or something like that.

If you do want to format it that way, you have to define an epsilon, that is, a maximum distance from an integer number, and use integer formatting if the difference is smaller, and a float otherwise.

Something like this would do the trick:

public String formatDecimal(float number) {
  float epsilon = 0.004f; // 4 tenths of a cent
  if (Math.abs(Math.round(number) - number) < epsilon) {
     return String.format("%10.0f", number); // sdb
  } else {
     return String.format("%10.2f", number); // dj_segfault
  }
}
Kevin Doyon
  • 3,464
  • 2
  • 33
  • 38
extraneon
  • 23,575
  • 2
  • 47
  • 51
  • 8
    Minor nitpick: a float can be exactly 100, with bit pattern 0x42c80000. – Karol S Aug 20 '14 at 20:11
  • 3
    Yes, as was stated by Karol S, many numbers CAN be exactly matched by floats. Just not ALL numbers. 100 is one number that can be represented, you should just account for numbers that can't be. – csga5000 Aug 29 '15 at 01:01
22

I did not find any good solution after google search, just post my solution for other to reference. use priceToString to format money.

public static String priceWithDecimal (Double price) {
    DecimalFormat formatter = new DecimalFormat("###,###,###.00");
    return formatter.format(price);
}

public static String priceWithoutDecimal (Double price) {
    DecimalFormat formatter = new DecimalFormat("###,###,###.##");
    return formatter.format(price);
}

public static String priceToString(Double price) {
    String toShow = priceWithoutDecimal(price);
    if (toShow.indexOf(".") > 0) {
        return priceWithDecimal(price);
    } else {
        return priceWithoutDecimal(price);
    }
}
wu liang
  • 1,993
  • 18
  • 12
  • 1
    He never said its a better one. HE just posted his solution so others can refer from it. Least you could say is a thanks. – Umang Desai Jan 02 '13 at 11:15
  • 1
    What if I want to display the price in Indian format. Without decimals. Format --> ##,##,### – Bhuvan Apr 30 '13 at 04:10
  • 1
    At priceWithDecimal(Double) method, try changing mask `"###,###,###.00"` to `"###,###,##0.00"` to show "0,00" when value is "0" – deldev Feb 12 '15 at 13:23
  • 1
    what will the vice-versa to converted the formatted currency to Double again – Vivek Shankar Apr 30 '15 at 09:43
10
NumberFormat currency = NumberFormat.getCurrencyInstance();
String myCurrency = currency.format(123.5);
System.out.println(myCurrency);

output:

$123.50

If you want to change the currency,

NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.CHINA);
String myCurrency = currency.format(123.5);
System.out.println(myCurrency);

output:

¥123.50
Subhashi
  • 4,145
  • 1
  • 23
  • 22
7

this best way to do that.

    public static String formatCurrency(String amount) {
        DecimalFormat formatter = new DecimalFormat("###,###,##0.00");
        return formatter.format(Double.parseDouble(amount));
    }

100 -> "100.00"
100.1 -> "100.10"

Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
6

I'm using this one (using StringUtils from commons-lang):

Double qty = 1.01;
String res = String.format(Locale.GERMANY, "%.2f", qty);
String fmt = StringUtils.removeEnd(res, ",00");

You must only take care of the locale and the corresponding String to chop.

Dirk Lachowski
  • 3,121
  • 4
  • 40
  • 66
5

you should do something like this:

public static void main(String[] args) {
    double d1 = 100d;
    double d2 = 100.1d;
    print(d1);
    print(d2);
}

private static void print(double d) {
    String s = null;
    if (Math.round(d) != d) {
        s = String.format("%.2f", d);
    } else {
        s = String.format("%.0f", d);
    }
    System.out.println(s);
}

which prints:

100

100,10

Stefan De Boey
  • 2,344
  • 16
  • 14
5

I think this is simple and clear for printing a currency:

DecimalFormat df = new DecimalFormat("$###,###.##"); // or pattern "###,###.##$"
System.out.println(df.format(12345.678));

output: $12,345.68

And one of possible solutions for the question:

public static void twoDecimalsOrOmit(double d) {
    System.out.println(new DecimalFormat(d%1 == 0 ? "###.##" : "###.00").format(d));
}

twoDecimalsOrOmit((double) 100);
twoDecimalsOrOmit(100.1);

Output:

100

100.10

Andrew
  • 36,676
  • 11
  • 141
  • 113
5

We will usually need to do the inverse, if your json money field is an float, it may come as 3.1 , 3.15 or just 3.

In this case you may need to round it for proper display (and to be able to use a mask on an input field later):

floatvalue = 200.0; // it may be 200, 200.3 or 200.37, BigDecimal will take care
Locale locale = new Locale("en", "US");      
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);

BigDecimal valueAsBD = BigDecimal.valueOf(value);
    valueAsBD.setScale(2, BigDecimal.ROUND_HALF_UP); // add digits to match .00 pattern

System.out.println(currencyFormatter.format(amount));
Renato Probst
  • 5,914
  • 2
  • 42
  • 45
4

I know this is an old question but...

import java.text.*;

public class FormatCurrency
{
    public static void main(String[] args)
    {
        double price = 123.4567;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.print(df.format(price));
    }
}
Aezur
  • 331
  • 2
  • 8
  • 3
    This doesn't work, it does 100.1 -> "100.1" for example - see http://stackoverflow.com/questions/5033404/how-to-use-javas-decimalformat-for-smart-currency-formatting – davnicwil Feb 15 '14 at 22:47
4

You can just do something like this and pass in the whole number and then the cents after.

String.format("$%,d.%02d",wholeNum,change);
user2645904
  • 169
  • 1
  • 2
  • 10
4

Yes. You can use java.util.formatter. You can use a formatting string like "%10.2f"

dj_segfault
  • 11,957
  • 4
  • 29
  • 37
  • `String.format()` is a nice static wrapper for that. Not sure why you use '10', though. – Xr. Mar 04 '10 at 12:50
  • Given no guidance on the size of the number, I chose 10 Ex Recto. We don't know if this is the price of a candy bar or a car. I believe you can also just do "%.2f" to leave the total size unbounded. – dj_segfault Mar 04 '10 at 13:09
  • 2
    DD wanted the decimal part omitted, if the amount is a round number of currency units. – jarnbjo Mar 04 '10 at 13:39
4

I agree with @duffymo that you need to use the java.text.NumberFormat methods for this sort of things. You can actually do all the formatting natively in it without doing any String compares yourself:

private String formatPrice(final double priceAsDouble) 
{
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    if (Math.round(priceAsDouble * 100) % 100 == 0) {
        formatter.setMaximumFractionDigits(0);
    }
    return formatter.format(priceAsDouble);
}

Couple bits to point out:

  • The whole Math.round(priceAsDouble * 100) % 100 is just working around the inaccuracies of doubles/floats. Basically just checking if we round to the hundreds place (maybe this is a U.S. bias) are there remaining cents.
  • The trick to remove the decimals is the setMaximumFractionDigits() method

Whatever your logic for determining whether or not the decimals should get truncated, setMaximumFractionDigits() should get used.

xbakesx
  • 13,202
  • 6
  • 48
  • 76
  • 1
    Re your point about the `*100` and `%100` being US-biased, you could use `Math.pow(10, formatter.getMaximumFractionDigits())` instead of a hard-coded `100` to use the correct number for the locale... – daiscog Sep 14 '15 at 14:02
3

Format from 1000000.2 to 1 000 000,20

private static final DecimalFormat DF = new DecimalFormat();

public static String toCurrency(Double d) {
    if (d == null || "".equals(d) || "NaN".equals(d)) {
        return " - ";
    }
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
    DecimalFormatSymbols symbols = DF.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');
    String ret = DF.format(bd) + "";
    if (ret.indexOf(",") == -1) {
        ret += ",00";
    }
    if (ret.split(",")[1].length() != 2) {
        ret += "0";
    }
    return ret;
}
Lukas
  • 391
  • 4
  • 11
2

If you want work on currencies, you have to use BigDecimal class. The problem is, there's no way to store some float numbers in memory (eg. you can store 5.3456, but not 5.3455), which can effects in bad calculations.

There's an nice article how to cooperate with BigDecimal and currencies:

http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html

Adrian Adamczyk
  • 3,000
  • 5
  • 25
  • 41
2

This post really helped me to finally get what I want. So I just wanted to contribute my code here to help others. Here is my code with some explanation.

The following code:

double moneyWithDecimals = 5.50;
double moneyNoDecimals = 5.00;
System.out.println(jeroensFormat(moneyWithDecimals));
System.out.println(jeroensFormat(moneyNoDecimals));

Will return:

€ 5,-
€ 5,50

The actual jeroensFormat() method:

public String jeroensFormat(double money)//Wants to receive value of type double
{
        NumberFormat dutchFormat = NumberFormat.getCurrencyInstance();
        money = money;
        String twoDecimals = dutchFormat.format(money); //Format to string
        if(tweeDecimalen.matches(".*[.]...[,]00$")){
            String zeroDecimals = twoDecimals.substring(0, twoDecimals.length() -3);
                return zeroDecimals;
        }
        if(twoDecimals.endsWith(",00")){
            String zeroDecimals = String.format("€ %.0f,-", money);
            return zeroDecimals; //Return with ,00 replaced to ,-
        }
        else{ //If endsWith != ,00 the actual twoDecimals string can be returned
            return twoDecimals;
        }
}

The method displayJeroensFormat that calls the method jeroensFormat()

    public void displayJeroensFormat()//@parameter double:
    {
        System.out.println(jeroensFormat(10.5)); //Example for two decimals
        System.out.println(jeroensFormat(10.95)); //Example for two decimals
        System.out.println(jeroensFormat(10.00)); //Example for zero decimals
        System.out.println(jeroensFormat(100.000)); //Example for zero decimals
    }

Will have the following output:

€ 10,50
€ 10,95
€ 10,-
€ 100.000 (In Holland numbers bigger than € 999,- and wit no decimals don't have ,-)

This code uses your current currency. In my case that's Holland so the formatted string for me will be different than for someone in the US.

  • Holland: 999.999,99
  • US: 999,999.99

Just watch the last 3 characters of those numbers. My code has an if statement to check if the last 3 characters are equal to ",00". To use this in the US you might have to change that to ".00" if it doesn't work already.

Jeroen
  • 21
  • 2
2

For the people who wants to format the currency, but does not want it to be based on local, we can do this:

val numberFormat = NumberFormat.getCurrencyInstance() // Default local currency
val currency = Currency.getInstance("USD")            // This make the format not locale specific 
numberFormat.setCurrency(currency)

...use the formator as you want...
Haomin
  • 1,265
  • 13
  • 12
1

This is what I did, using an integer to represent the amount as cents instead:

public static String format(int moneyInCents) {
    String format;
    Number value;
    if (moneyInCents % 100 == 0) {
        format = "%d";
        value = moneyInCents / 100;
    } else {
        format = "%.2f";
        value = moneyInCents / 100.0;
    }
    return String.format(Locale.US, format, value);
}

The problem with NumberFormat.getCurrencyInstance() is that sometimes you really want $20 to be $20, it just looks better than $20.00.

If anyone finds a better way of doing this, using NumberFormat, I'm all ears.

Viktor Nordling
  • 8,694
  • 4
  • 26
  • 23
1

I was crazy enough to write my own function:

This will convert integer to currency format (can be modified for decimals as well):

 String getCurrencyFormat(int v){
        String toReturn = "";
        String s =  String.valueOf(v);
        int length = s.length();
        for(int i = length; i >0 ; --i){
            toReturn += s.charAt(i - 1);
            if((i - length - 1) % 3 == 0 && i != 1) toReturn += ',';
        }
        return "$" + new StringBuilder(toReturn).reverse().toString();
    }
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
0
  public static String formatPrice(double value) {
        DecimalFormat formatter;
        if (value<=99999)
          formatter = new DecimalFormat("###,###,##0.00");
        else
            formatter = new DecimalFormat("#,##,##,###.00");

        return formatter.format(value);
    }
PRATEEK BHARDWAJ
  • 2,364
  • 2
  • 21
  • 35
0
double amount = 200.0;

NumberFormat Us = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(Us.format(amount));

Output:
$200.00

GURU Shreyansh
  • 881
  • 1
  • 7
  • 19