Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to format a price

Short answer

NumberFormat.getCurrencyInstance() formats an amount by the rules of a country — the currency symbol, separators and number of cents:

void main() {
    var price = new BigDecimal("1234.5");
 
    IO.println(NumberFormat.getCurrencyInstance(Locale.US).format(price));
    IO.println(NumberFormat.getCurrencyInstance(Locale.GERMANY).format(price));
}

Output:

$1,234.50
1.234,50 €

The German format uses a non-breaking space before €.

A simple format

If country rules do not matter, String.format() with a locale is enough:

void main() {
    double total = 1234.5;
    IO.println(String.format(Locale.US, "$%,.2f", total));
}

Output:

$1,234.50

Another currency

To show euros in the US format, set the currency separately:

void main() {
    NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
    format.setCurrency(Currency.getInstance("EUR"));
 
    IO.println(format.format(99.9));
}

Output:

€99.90

Without cents

For round amounts drop the fractional part:

void main() {
    NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
    format.setMaximumFractionDigits(0);
 
    IO.println(format.format(2500));
}

Output:

$2,500

Common mistake

Gluing a currency symbol to a double directly. The number is shown without cents or with extra digits:

void main() {
    IO.println("$" + 10.0);
    IO.println("$" + 0.1 * 3);
}

Output:

$10.0
$0.30000000000000004

Functions used in this recipe

  • NumberFormat — Formats numbers, money and percentages by the rules of a chosen country.
  • BigDecimal — An exact decimal number — for money and calculations where double rounding errors are unacceptable.
  • String.format() — Builds a string from a template with placeholders such as %s and %d.

Thanks for reading!

Donate to the site — we work hard for you.