Locale and formatting
What you will learn
Localization adapts presentation to a user’s language and region without changing stored values. A locale controls conventions such as decimal separators, language and collation; a time zone determines the local time of an instant. Keep both choices explicit.
- Format dates, numbers and currency using explicit locale and zone.
- Parse strict dates and validate complete numeric input.
- Explain message bundles, Unicode normalization and right-to-left display boundaries.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Display an exact amount in different locales
import java.math.*;import java.time.*;import java.time.format.*;import java.time.temporal.*;import java.text.*;import java.util.*;public class Main { public static void main(String[] args) throws Exception { BigDecimal amount = new BigDecimal("1234.50"); NumberFormat us = NumberFormat.getCurrencyInstance(Locale.US); NumberFormat de = NumberFormat.getCurrencyInstance(Locale.GERMANY); for (NumberFormat f : List.of(us,de)) { f.setCurrency(Currency.getInstance("USD")); f.setMinimumFractionDigits(2); f.setMaximumFractionDigits(2); } System.out.println(us.format(amount)); System.out.println(de.format(amount).contains("1.234,50")); System.out.println(de.getCurrency().getCurrencyCode()); }}Expected output:
$1,234.50trueUSDThe same USD amount has different presentation. The German test deliberately avoids asserting placement or exact whitespace around the currency symbol; the US example is pinned to the tested JDK data.
Formatting is not storage
Keep exact decimal amounts plus currency codes and instants or dates in the domain model. NumberFormat.getCurrencyInstance(locale) chooses presentation conventions; explicitly set the currency and fraction digits according to your domain policy when necessary. Changing currency does not perform exchange or automatically update every formatting setting. Locale is not a time zone or a guarantee of currency preference. DateTimeFormatter is immutable and thread-safe; NumberFormat and Collator should not be shared across threads without appropriate coordination. Localized text and collation may vary with JDK locale data and provider; assert stable properties or pin the environment when testing exact text.
Parsing and formatting boundaries
Use DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ROOT).withResolverStyle(ResolverStyle.STRICT) for a strict ISO-style date pattern; uuuu means proleptic year, yyyy means year of era. Use ISO_INSTANT for machine timestamps. To format an Instant with local fields, attach a zone to the formatter or convert to ZonedDateTime first. A NumberFormat parser can accept only a prefix; check ParsePosition for full consumption and apply business validation. DecimalFormat.setParseBigDecimal(true) requests BigDecimal for ordinary finite numeric values; do not assume special values such as NaN are valid amounts.
Language, normalization and direction
ResourceBundle selects messages by locale with fallback rules; in an application use reviewed resources and explicit fallback policy. The example uses an in-memory ListResourceBundle to avoid file and deployment dependencies. Collator provides language-sensitive ordering; it can consider distinct strings equivalent, so do not substitute it for identifier equality. Normalizer NFC makes canonically equivalent sequences comparable under a chosen policy, but does not solve all confusables or spelling differences. Persian text is right-to-left: present it with appropriate RTL container direction in the UI and isolate LTR identifiers, ISO timestamps and code using semantic markup (such as bdi). Never reverse strings manually or assume a locale switches the calendar to the Persian calendar; this example explicitly uses ISO dates. Translation content remains English-only; Persian is used solely as a sample string. Renderer direction and font behavior require separate visual testing.
Format an instant and parse strict dates
import java.math.*;import java.time.*;import java.time.format.*;import java.time.temporal.*;import java.text.*;import java.util.*;public class Main { public static void main(String[] args) throws Exception { var formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm",Locale.ROOT).withZone(ZoneId.of("Europe/Stockholm")); System.out.println(formatter.format(Instant.parse("2024-06-01T23:30:00Z"))); var strict = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ROOT).withResolverStyle(ResolverStyle.STRICT); System.out.println(LocalDate.parse("2024-02-29",strict)); try { LocalDate.parse("2023-02-29",strict); } catch(DateTimeParseException ex) { System.out.println("invalid date"); } }}Expected output:
2024-06-02 01:302024-02-29invalid dateAn explicit zone controls the displayed date; strict resolution rejects a nonexistent leap day.
Parse the entire numeric field
import java.math.*;import java.time.*;import java.time.format.*;import java.time.temporal.*;import java.text.*;import java.util.*;public class Main { public static void main(String[] args) throws Exception { DecimalFormat f = (DecimalFormat) NumberFormat.getNumberInstance(Locale.GERMANY); f.setParseBigDecimal(true); for (String input : List.of("12,50", "12,50xyz")) { ParsePosition pos = new ParsePosition(0); Number n = f.parse(input,pos); if (n instanceof BigDecimal d && pos.getIndex()==input.length()) System.out.println(d.toPlainString()); else System.out.println("invalid amount"); } }}Expected output:
12.50invalid amountThe parser may stop before trailing junk. Full consumption is necessary but does not enforce every domain constraint, such as allowed grouping or amount range.
Messages, normalization and collation
import java.math.*;import java.time.*;import java.time.format.*;import java.time.temporal.*;import java.text.*;import java.util.*;public class Main { public static void main(String[] args) throws Exception { ResourceBundle messages = new ListResourceBundle() { protected Object[][] getContents() { return new Object[][]{{"ready", "آماده"}}; } }; System.out.println(messages.getString("ready").equals("آماده")); String composed = "é", decomposed = "e\u0301"; System.out.println(composed.equals(decomposed)); System.out.println(Normalizer.normalize(decomposed,Normalizer.Form.NFC).equals(composed)); Collator c = Collator.getInstance(Locale.FRENCH); c.setStrength(Collator.PRIMARY); System.out.println(c.compare("e","é")==0); }}Expected output:
truefalsetruetrueThe sample message is stored in logical order, not reversed. NFC reconciles canonical forms; the French primary-strength comparison ignores the accent in this example. This tests strings, not screen layout or locale fallback.
Common mistakes
Do not infer a time zone or currency from a locale alone. Do not store formatted currency as the authoritative amount. Never accept partial numeric parses unnoticed or assume yyyy and uuuu behave identically under strict parsing. Use explicit UTF-8 resources and test direction in the actual renderer; a successful Java string comparison is not proof of correct RTL layout.
Practice
Format the fixed instant 2024-01-01T23:30:00Z in UTC and Europe/Stockholm with the pattern uuuu-MM-dd HH:mm and Locale.ROOT. Then format 25.50 USD with Locale.US, specifying the currency and two fraction digits.
Expected output:
2024-01-01 23:302024-01-02 00:30$25.50Compare your answer with the manual practice criteria.
Official reading: NumberFormat · Locale · DateTimeFormatter. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Locale and formatting — knowledge check
Original arithmetic, time and localization questions. Java 21-compatible scope.
What determines the local date of an instant?
Which pattern letter represents proleptic year?
How can trailing junk in NumberFormat parsing be detected?
What does NFC normalization resolve?
Does changing the currency of NumberFormat convert the amount?