public static String currencyFormat(BigDecimal n) {
    return NumberFormat.getCurrencyInstance().format(n);
}

It will use your JVM’s current default Locale to choose your currency symbol. Or you can specify a Locale.

NumberFormat.getInstance(Locale.US)

For more info, see NumberFormat class.

Answer from Luca Molteni on Stack Overflow
Top answer
1 of 9
95

Here are a few hints:

  1. Use BigDecimal for computations if you need the precision that it offers (Money values often need this).
  2. Use the NumberFormat class for display. This class will take care of localization issues for amounts in different currencies. However, it will take in only primitives; therefore, if you can accept the small change in accuracy due to transformation to a double, you could use this class.
  3. When using the NumberFormat class, use the scale() method on the BigDecimal instance to set the precision and the rounding method.

PS: In case you were wondering, BigDecimal is always better than double, when you have to represent money values in Java.

PPS:

Creating BigDecimal instances

This is fairly simple since BigDecimal provides constructors to take in primitive values, and String objects. You could use those, preferably the one taking the String object. For example,

BigDecimal modelVal = new BigDecimal("24.455");
BigDecimal displayVal = modelVal.setScale(2, RoundingMode.HALF_EVEN);

Displaying BigDecimal instances

You could use the setMinimumFractionDigits and setMaximumFractionDigits method calls to restrict the amount of data being displayed.

NumberFormat usdCostFormat = NumberFormat.getCurrencyInstance(Locale.US);
usdCostFormat.setMinimumFractionDigits( 1 );
usdCostFormat.setMaximumFractionDigits( 2 );
System.out.println( usdCostFormat.format(displayVal.doubleValue()) );
2 of 9
40

I would recommend a little research on Money Pattern. Martin Fowler in his book Analysis pattern has covered this in more detail.

public class Money {

    private static final Currency USD = Currency.getInstance("USD");
    private static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN;

    private final BigDecimal amount;
    private final Currency currency;   

    public static Money dollars(BigDecimal amount) {
        return new Money(amount, USD);
    }

    Money(BigDecimal amount, Currency currency) {
        this(amount, currency, DEFAULT_ROUNDING);
    }

    Money(BigDecimal amount, Currency currency, RoundingMode rounding) {
        this.currency = currency;      
        this.amount = amount.setScale(currency.getDefaultFractionDigits(), rounding);
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public Currency getCurrency() {
        return currency;
    }

    @Override
    public String toString() {
        return getCurrency().getSymbol() + " " + getAmount();
    }

    public String toString(Locale locale) {
        return getCurrency().getSymbol(locale) + " " + getAmount();
    }   
}

Coming to the usage:

You would represent all monies using Money object as opposed to BigDecimal. Representing money as big decimal will mean that you will have the to format the money every where you display it. Just imagine if the display standard changes. You will have to make the edits all over the place. Instead using the Money pattern you centralize the formatting of money to a single location.

Money price = Money.dollars(38.28);
System.out.println(price);
🌐
InfoWorld
infoworld.com › home › software development › programming languages › java
Make cents with BigDecimal | InfoWorld
June 1, 2001 - The NumberFormat class, found in the java.text library, can create an appropriate object for US currency with the following code: NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); Note that the Locale class, used as an argument for the getCurrencyInstance() method above, is found ...
🌐
Stevenschwenke
stevenschwenke.de › formattingCurrencyInJavaWithStringFormat
Formatting Currency in Java with string.format
After searching for a while and wondering why so many libraries exist, a colleague found a surprisingly easy solution: String.format(). Here is some code to show how to format currency with plain Java. void formatCurrency(BigDecimal value) { // %, => local-specific thousands separator // .2f => positions after decimal point return String.format("%,.2f", price); } @Test void formattingOfBigDecimalToString() { BigDecimal priceToFormat = BigDecimal.valueOf(23356); String formattedPrice = formatCurrency(priceToFormat); assertEquals("23.356,00", formattedPrice); priceToFormat = BigDecimal.valueOf(3
🌐
Coderanch
coderanch.com › t › 417309 › java › Big-Decimal-Currency-Formatting
Big Decimal Currency Formatting (Java in General forum at Coderanch)
Check the development machine for its currency symbol. Perhaps it is � or €. SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Thank you Campbell and Rob for your prompt replies. I just wanted to make sure if its really an environmental issue. Also the Unicode chart helps, I will definitely play with it in java. Thanks again. [ November 11, 2008: Message edited by: Himalay Majumdar ] ... Just after a day I posted the formatting question, another build took place in development and surprisingly the development environment is now showing $15.00 and NOT ?15.00.
🌐
Java2s
java2s.com › Book › Java › Examples › Format_BigDecimal_to_Currency_and_Percentage.htm
Format BigDecimal to Currency and Percentage Java Book
import java.text.NumberFormat; public · class Main { public · static · void main(String[] args) { double subtotal = 123.123; BigDecimal decimalSubtotal = new BigDecimal(Double.toString(subtotal)); NumberFormat currency = NumberFormat.getCurrencyInstance(); NumberFormat percent = ...
🌐
Alvin Alexander
alvinalexander.com › scala › scala-3-how-format-numbers-currency-bigdecimal
Scala 3: How to format numbers and currency | alvinalexander.com
import java.util.{Currency, Locale} val deCurrency = Currency.getInstance(Locale.GERMANY) val deFormatter = java.text.NumberFormat.getCurrencyInstance deFormatter.setCurrency(deCurrency) deFormatter.format(123.456789) // €123.46 deFormatter.format(12_345.6789) // €12,345.68 deFormatter.format(1_234_567.89) // €1,234,567.89 · If you don’t use a currency library you’ll probably want to use BigDecimal, which also works with getCurrencyInstance.
🌐
GitHub
gist.github.com › dhatch › 2520974
Example of Java number formatting options · GitHub
Example of Java number formatting options. GitHub Gist: instantly share code, notes, and snippets.
🌐
Educative
educative.io › answers › how-to-format-a-number-as-currency-depending-on-locale-in-java
How to format a number as currency depending on Locale in Java
getCurrencyInstance() is a static method of the NumberFormat class that returns the currency format for the specified locale. Note: A Locale in Java represents a specific geographical, political, or cultural region. public static NumberFormat ...
Find elsewhere
🌐
Tabnine
tabnine.com › home page › code › java › java.text.numberformat
java.text.NumberFormat.getCurrencyInstance java code examples | Tabnine
String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber); //Handle the weird exception of formatting whole dollar amounts with no decimal currencyString = currencyString.replaceAll("\\.00", ""); ... double amt = 123.456; NumberFormat formatter = NumberFormat.getCurrencyInstance(); System.out.println(formatter.format(amt)); ... public static void main(String[] args) throws Exception { final String s = "8890"; final BigDecimal dec = new BigDecimal(s).divide(BigDecimal.valueOf(100)); final String formatted = DecimalFormat.getCurrencyInstance(Locale.FRANCE).format(dec); System.out.println(formatted); }
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-convert-a-string-to-a-currency-format
Java Program to Convert a String to a Currency Format - GeeksforGeeks
July 23, 2025 - We use the format() method of each NumberFormat instance to format the BigDecimal amount as a currency string for each currency. Finally, we print the formatted currency strings to the console.
🌐
Spring
docs.spring.io › spring-framework › docs › 3.0.x › javadoc-api › org › springframework › format › number › CurrencyFormatter.html
CurrencyFormatter
java.lang.Object org.springframework.format.number.AbstractNumberFormatter org.springframework.format.number.CurrencyFormatter ... A BigDecimal formatter for currency values.
🌐
Ficoanalyticcloud
help-svc.prd-platform.ficoanalyticcloud.com › decisionexecutor_1.4 › GUID-8F868565-57E0-4371-8905-16090CE5623E.html
format(BigDecimal):string
format(BigDecimal bigDecimal):string The argument bigDecimal is a numeric value that uses the directives as defined by the java.math.BigDecimal class. bigDecimal is some BigDecimal initially BigDecimal.newInstance(100.0). print("Value of bigDecimal is " currencies().format(bigDecimal). Value of bigDecimal is 100. Parent Topic: Currency Built-in Functions ·
🌐
Baeldung
baeldung.com › home › java › java numbers › number formatting in java
Number Formatting in Java | Baeldung
August 9, 2024 - In Java, we have two primitive types that represent decimal numbers, float and decimal: double myDouble = 7.8723d; float myFloat = 7.8723f; The number of decimal places can be different depending on the operations being performed. In most cases, we’re only interested in the first couple of decimal places. Let’s take a look at some ways to format a decimal by rounding. The BigDecimal ...
Top answer
1 of 3
13

It all comes down to precision, and Java's BigDecimal seems the correct answer on that platform because it gives you the best support for specifying and preserving what can be highly variable precision.

A millionth of a cent is only 10-5 from a shift in payable amount, and it's not that hard to come up with a situation where that level of precision matters.

  1. Company A is publicly traded, with fifty million (5x106) shares outstanding and a current price of $10.
  2. Person B buys $1 of Company A, through a broker. They now own one-tenth of a share, or a one five-hundred-millionth of Company A. (10-7).
  3. Company A is found to be absurdly over-valued, and after a bit of a scandal winds up accepting a stock-swap purchase by Company C at a value of $1,000 (103), with each shareholder getting the equivalent number to be paid out equally to the shareholders in either cash or stock.
  4. How much cash or stock can Person B get? Note that if you get the number wrong, Person B (who happens to be an out-of-work lawyer in his 30s) can mess up the entire deal and possibly earn himself a paycheck by suing for his value lost plus legal fees.

Now, the valuation is fairly absurd on purpose, but the same "you need to get it right or it explodes" details even if the numbers are only off by a minuscule amount.

2 of 3
9

The right type to represent currency values depends of the application.

Two plausible choices are a type capable of exact arithmetic or a floating point type. Please remember two facts:

  1. In floating point arithmetic, usual algebraic identities (like commutativity and associativity) does not hold any more. They still hold in exact arithmetic.

  2. In exact arithmetic, it is not possible to work with functions other than polynomials, so we cannot use the square root or the exponential functions. Floating point arithmetics allows to use them.

In a double accounting personal finance software, exact arithmetic is preferrable. We expect all of the cashflows recorded to sum up to zero. Since this is an algebraic identity, we can only verify it if we use exact arithmetics. Here using a floating point would make the whole principe of double accounting useless.

In an internal software used by a clearing house, exact arithmetic is also mandatory, basically for the same reason as previously. There is a conservation principle, so that cashflows should always sum up to zero. Since the program has to satisfy an invariant of an algebraic nature, it must rely on exact arithmetics.

In a pricing or risk management software implementing methods of mathematical finance, complex computations reminescent of physics simulations are performed and expectations estimates are computed. The very nature of this problem require the use of floating point numbers.

🌐
GitHub
gist.github.com › jimmyFlash › a6000e49c9c5cfb79f716834cd8e2fb9
Convert a currency formatted string to BigDecimal (double shouldn't be used to represent precision amounts) · GitHub
Convert a currency formatted string to BigDecimal (double shouldn't be used to represent precision amounts) - CurrencyAmoutBdecimalConverter.java
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Representing money
It may appear in the database in the following ways : * <ul> * <li>as <code>123456.78</code>, with the usual number of decimal places * associated with that currency. * <li>as <code>123456</code>, without any decimal places at all. * <li>as <code>123</code>, in units of thousands of dollars.
🌐
Altimetrik
altimetrik.com › home › blog › mastering monetary operations: navigating currency handling in java
Mastering Monetary Operations: Navigating Currency Handling in Java - Altimetrik
December 5, 2024 - This not only ensures precision but also enhances code readability and maintainability. It describes how to create a class representing monetary amount, which will take care of currency verification, rounding, formatting, comparison, and some other utility methods. public class Money { private BigDecimal amount; private Currency currency; }
🌐
Christopher Siu
users.csc.calpoly.edu › ~jdalbey › SWE › SampleCode › Money.java
Money.java
Specifies if and how the monetary value is * to be rounded off to an integral cent. */ protected int roundingMode = BigDecimal.ROUND_DOWN; // Rounding Mode /** * The Currency Format, used for formatting and parsing a * monetary value. Refer to the Java API * documentation for the DecimalFormat ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › text › DecimalFormat.html
DecimalFormat (Java Platform SE 7 )
Gets the minimum number of digits allowed in the fraction portion of a number. For formatting numbers other than BigInteger and BigDecimal objects, the lower of the return value and 340 is used. ... Gets the currency used by this decimal format when formatting currency values.