Course contentsShow
← Java
Lesson 2230 of 2,87043. String Handling in DepthFree lesson

Locale-Aware Formatting

Handling locale-specific number and date formatting with formatted vs String.format behavior.

Locale-Aware Formatting

You'll learn how formatting methods behave differently based on locale settings, affecting how numbers and dates appear to users worldwide.

When you use formatted() or String.format(), Java can adapt the output to match regional conventions—thousands separators, decimal points, currency symbols, and date formats all vary by culture. A German user expects 1.234,56 while an American expects 1,234.56 for the same number.

How Locale Affects Formatting

By default, String.format() uses the JVM's default locale. To explicitly control this, you pass a Locale object:

double price = 1234.56;

// Uses default locale
String defaultFormatted = "Price: %.2f".formatted(price);

// Explicitly US locale (period as decimal separator)
String usFormatted = String.format(Locale.US, "Price: %.2f", price);

// Explicitly German locale (comma as decimal separator)
String deFormatted = String.format(Locale.GERMANY, "Price: %.2f", price);

The German version outputs 1234,56 while the US version outputs 1234.56—same data, different presentation.

Practical Implications

The formatted() instance method uses the default locale and cannot accept a custom Locale parameter. If you need locale control, you must use the static String.format(Locale, String, Object...) method instead.

This matters when building internationalized applications: hard-coding format strings without locale awareness can confuse users or even break data parsing. For instance, displaying prices to European customers with American formatting looks unprofessional.

Think of It Like This

Locale formatting is like automatic translation for numbers—the underlying value stays the same, but the "spelling" changes to match local conventions.

Key Takeaway:
Use String.format(Locale, ...) when you need explicit locale control for formatting; formatted() always uses the default locale and cannot be customized per-call.