Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to format a string with values

Short answer

String.format() puts values in place of placeholders: %s is a string, %d an integer, %.2f a decimal with two digits:

void main() {
    String text = String.format("%s bought %d items for %.2f €", "Anna", 3, 17.5);
    IO.println(text);
}

Output:

Anna bought 3 items for 17.50 €

The formatted method

formatted() does the same thing, but is called on the template string itself:

void main() {
    IO.println("%s is %d years old".formatted("Oleg", 30));
}

Output:

Oleg is 30 years old

Width and alignment

A number after % sets the field width, a minus aligns to the left. This gives you neat tables:

void main() {
    IO.println("%-8s|%6s".formatted("Item", "Price"));
    IO.println("%-8s|%6.2f".formatted("Tea", 3.5));
    IO.println("%-8s|%6.2f".formatted("Cake", 12.25));
}

Output:

Item    | Price
Tea     |  3.50
Cake    | 12.25

Leading zeros and separators

The 0 flag pads a number with zeros, the , flag adds a thousands separator:

void main() {
    IO.println("%05d".formatted(42));
    IO.println("%,d".formatted(1234567));
}

Output:

00042
1,234,567

Common mistake

Passing a value of the wrong type. %d accepts integers only:

void main() {
    IO.println("%d".formatted(3.5));
}

Output:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double

Use %f or %.2f for decimals. Note that %f and %,d use the system language: on a computer with a German locale the fractional part is separated by a comma. To make the result independent of the computer, pass a locale: String.format(Locale.US, ...).

Functions used in this recipe

  • String.format() — Builds a string from a template with placeholders such as %s and %d.
  • String.formatted() — Uses the string itself as a template and fills it in — a shorter form of String.format().
  • System.out.printf() — Prints a string built from a template with %s, %d, %.2f placeholders.

Thanks for reading!

Donate to the site — we work hard for you.