Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to format a number with thousands separators

Short answer

The , flag in a String.format() pattern adds group separators:

void main() {
    IO.println(String.format(Locale.US, "%,d", 1234567));
    IO.println(String.format(Locale.US, "%,.2f", 9876543.219));
}

Output:

1,234,567
9,876,543.22

By country rules

Different countries separate digits differently. NumberFormat knows the rules:

void main() {
    long population = 83_200_000;
 
    IO.println(NumberFormat.getInstance(Locale.US).format(population));
    IO.println(NumberFormat.getInstance(Locale.GERMANY).format(population));
    IO.println(NumberFormat.getInstance(Locale.of("ru")).format(population));
}

Output:

83,200,000
83.200.000
83 200 000

The Russian format separates digits with a non-breaking space.

A custom pattern

DecimalFormat sets the format with a pattern: # is a digit if present, 0 is always a digit:

void main() {
    var format = new DecimalFormat("#,##0.00", DecimalFormatSymbols.getInstance(Locale.US));
 
    IO.println(format.format(1234.5));
    IO.println(format.format(0.5));
}

Output:

1,234.50
0.50

Compact notation

NumberFormat.getCompactNumberInstance() turns large numbers into short forms like "2K" and "2M". By default the value is rounded to a whole number:

void main() {
    var format = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
 
    IO.println(format.format(1_500));
    IO.println(format.format(2_300_000));
}

Output:

2K
2M

Common mistake

Parsing a formatted string back with parseInt(). The separators get in the way:

void main() {
    IO.println(Integer.parseInt("1,234"));
}

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1,234"

Use NumberFormat.getInstance(Locale.US).parse("1,234") or remove the separators first.

Functions used in this recipe

  • String.format() — Builds a string from a template with placeholders such as %s and %d.
  • NumberFormat — Formats numbers, money and percentages by the rules of a chosen country.

Thanks for reading!

Donate to the site — we work hard for you.