How to format decimals in a currency format?

JavaCurrencyNumber Formatting

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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);
    }
}

Solution 2 - Java

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

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

Solution 3 - Java

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
  }
}

Solution 4 - Java

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);
    }
}

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

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"

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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));

Solution 11 - Java

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

Solution 12 - Java

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));
    }
}

Solution 13 - Java

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

String.format("$%,d.%02d",wholeNum,change);

Solution 14 - Java

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.

Solution 15 - Java

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;
}

Solution 16 - Java

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

Solution 17 - Java

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,5010,9510,-
€ 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.

Solution 18 - Java

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

Solution 19 - Java

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.

Solution 20 - Java

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();
    }

Solution 21 - Java

  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);
    }

Solution 22 - Java

double amount = 200.0;

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

Output:
$200.00

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDD.View Question on Stackoverflow
Solution 1 - JavaduffymoView Answer on Stackoverflow
Solution 2 - JavaThilina DharmasenaView Answer on Stackoverflow
Solution 3 - JavaextraneonView Answer on Stackoverflow
Solution 4 - Javawu liangView Answer on Stackoverflow
Solution 5 - JavaSubhashiView Answer on Stackoverflow
Solution 6 - JavaDirk LachowskiView Answer on Stackoverflow
Solution 7 - JavaSamet ÖZTOPRAKView Answer on Stackoverflow
Solution 8 - JavaStefan De BoeyView Answer on Stackoverflow
Solution 9 - JavaAndrewView Answer on Stackoverflow
Solution 10 - JavaRenato ProbstView Answer on Stackoverflow
Solution 11 - Javadj_segfaultView Answer on Stackoverflow
Solution 12 - JavaAezurView Answer on Stackoverflow
Solution 13 - Javauser2645904View Answer on Stackoverflow
Solution 14 - JavaxbakesxView Answer on Stackoverflow
Solution 15 - JavaLukasView Answer on Stackoverflow
Solution 16 - JavaAdrian AdamczykView Answer on Stackoverflow
Solution 17 - JavaJeroenView Answer on Stackoverflow
Solution 18 - JavaHaominView Answer on Stackoverflow
Solution 19 - JavaViktor NordlingView Answer on Stackoverflow
Solution 20 - JavaA-SharabianiView Answer on Stackoverflow
Solution 21 - JavaPRATEEK BHARDWAJView Answer on Stackoverflow
Solution 22 - JavaRIZA ÖZERView Answer on Stackoverflow