Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

NumberFormat

Formats numbers, money and percentages by the rules of a chosen country.

Available since: Java 1.1

Syntax

public abstract class NumberFormat extends Format

Examples

One number in different locales:

void main() {
    double amount = 1234567.891;
    IO.println(NumberFormat.getInstance(Locale.US).format(amount));
    IO.println(NumberFormat.getInstance(Locale.GERMANY).format(amount));
    IO.println(NumberFormat.getCurrencyInstance(Locale.US).format(amount));
    IO.println(NumberFormat.getPercentInstance(Locale.US).format(0.256));
}

Output:

1,234,567.891
1.234.567,891
$1,234,567.89
26%

Compact notation (Java 12) and parsing a string with a comma:

void main() throws Exception {
    var compact = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
    IO.println(compact.format(1_250_000));
    IO.println(NumberFormat.getInstance(Locale.GERMANY).parse("3,14"));
}

Output:

1M
3.14

Notes

Always pass a locale explicitly: without it the system settings are used and the output differs between computers. The class is in the java.text package; instances are not thread-safe. For simple output with two decimals String.format(Locale.ROOT, "%.2f", x) is often enough.

See also

  • String.format() — Builds a string from a template with placeholders such as %s and %d.
  • BigDecimal — An exact decimal number — for money and calculations where double rounding errors are unacceptable.
  • Double.parseDouble() — Converts a string with a decimal number to a double.

Related recipes

In the tutorial

  • Text blocks and formatting — Multi-line text blocks in Java, formatting strings with formatted, String.format and printf, the %s, %d and %f specifiers and field width.

Thanks for reading!

Donate to the site — we work hard for you.