Java Locales: Localizing Numbers, Currency, Percentages, Compact Numbers and Dates (OCP 21)
Localization for the OCP 21 exam: Locale format and creation with constants, Locale.of and Locale.Builder, NumberFormat factories for numbers, currency, percent and integers, locale-aware parsing, CompactNumberFormat SHORT and LONG, localized date/time styles, and Locale.Category.
kvi5hnuCode Sprout team member7 min readOn this page
Is 4/1/26 the 1st of April or the 4th of January? Is 1.234 a little more than one, or a little more than a thousand? It depends on who's reading. Two terms describe how programs handle this:
- Internationalization (i18n) means designing a program so it can adapt: text kept outside the code, and formatting done through locale-aware classes.
- Localization (l10n) means supporting particular locales: translated text, and dates and numbers in local conventions.
A program can be internationalized long before it's localized for anyone.
Locale
A java.util.Locale identifies a language, optionally with a country (the API calls it a region). Its toString() format is the one the exam tests:

| Valid | Invalid, and why |
|---|---|
en | US: a country without a language |
en_US | enUS: missing underscore |
fr_CA | US_en: country and language reversed |
es_MX | EN: the language must be lowercase |
You don't need to memorize codes. If the exam shows es_CO, you only need to know that es is the language and CO the country.
Getting a Locale
Locale.getDefault(); // e.g. en_US: whatever the JVM started with
Locale.GERMAN; // de (language only)
Locale.GERMANY; // de_DE (language + country)
Locale.of("it"); // it Java 19+
Locale.of("es", "MX"); // es_MX Java 19+
new Locale.Builder().setRegion("JP").setLanguage("ja").build(); // ja_JP; any order
Locale.forLanguageTag("fr-CA"); // fr_CA (IETF tag with a hyphen)
new Locale("en", "US"); // DEPRECATED since Java 19
Locale.of (Java 19) replaced the public constructors, which are now deprecated. Older books and code use new Locale(...). It still compiles, with a deprecation warning.
Java doesn't validate codes. Locale.of("xx", "XX") works, but it won't match any real formatting data, so you silently get fallback behaviour. Locale.of also normalizes case: Locale.of("EN", "us") prints en_US.
Locale.setDefault(Locale.of("fr")) changes the default for the running JVM only. It doesn't touch the operating system or later runs. Exam code often calls it so the output doesn't depend on where you are.
Localizing numbers
Every number formatter comes from a NumberFormat factory. Each factory has a no-argument version, which uses the default locale, and a (Locale) version:
| Factory | Formats | US example | GERMANY example |
|---|---|---|---|
getInstance() / getNumberInstance() (same thing) | general numbers (up to 3 decimals) | 1,234,567.891 | 1.234.567,891 |
getCurrencyInstance() | money | $48.50 | 48,50 € |
getPercentInstance() | ×100 with % | 80% | 80 % |
getIntegerInstance() | rounds to a whole number (HALF_EVEN) | 2.5 → 2, 3.5 → 4 | |
getCompactNumberInstance(), or (Locale, NumberFormat.Style) | short forms | 7M, 7 million | 7 Mio., 7 Millionen |
double price = 48.5;
NumberFormat.getCurrencyInstance(Locale.US).format(price); // $48.50
NumberFormat.getCurrencyInstance(Locale.UK).format(price); // £48.50
NumberFormat.getCurrencyInstance(Locale.JAPAN).format(price); // ¥48 (no minor unit; HALF_EVEN)
NumberFormat.getPercentInstance(Locale.US).format(0.8025); // 80%
The "spaces" in German, French and other output are non-breaking spaces (U+00A0, or the narrow U+202F), not ordinary spaces. The example program makes them visible. Comparing formatted output with a hand-typed " " is a classic real-world bug.
Use BigDecimal or whole cents for real money, never double. The exam uses double only for simplicity.
Parsing is locale-aware too
parse returns a Number (usually a Long or Double) and throws the checked ParseException if the text doesn't start with a number:
String text = "40.45";
NumberFormat.getInstance(Locale.US).parse(text); // 40.45
NumberFormat.getInstance(Locale.FRANCE).parse(text); // 40 ('.' isn't a French number symbol: stop)
NumberFormat.getInstance(Locale.GERMANY).parse(text); // 4045 ('.' is the German grouping separator!)
double income = (Double) NumberFormat.getCurrencyInstance(Locale.US).parse("$92,807.99"); // 92807.99
NumberFormat.getCurrencyInstance(Locale.US).parse("92.5"); // ParseException: no $ sign
Parse with the locale the text was written in. The wrong locale doesn't always throw. It can quietly give a wrong number.
CompactNumberFormat
The second concrete NumberFormat subclass the exam expects is CompactNumberFormat, for places where space is tight. It picks the largest unit (thousand, million, billion, trillion), rounds to a whole number of that unit by default (HALF_EVEN), and adds a label:
| Value | US SHORT (the default style) | US LONG | GERMANY SHORT | GERMANY LONG |
|---|---|---|---|---|
| 7,123,456 | 7M | 7 million | 7 Mio. | 7 Millionen |
| 314,900,000 | 315M | 315 million | 315 Mio. | 315 Millionen |
| 1,550,000,000 | 2B | 2 billion | 2 Mrd. | 2 Milliarden |
| 950 | 950 | 950 | 950 | 950 |
SHORTuses a symbol, andLONGuses a space and a word.- Values below 1,000 are printed as-is.
NumberFormat.Styleis a nested enum with the valuesSHORTandLONG.- Labels and rounding thresholds come from the JDK's locale data (CLDR), so a few locales print differently between JDK versions. For example, JDK 21 and JDK 25 differ for
fr_FRLONG. The exam sticks toUS-style examples.
Parsing accepts both forms, but stops at punctuation it doesn't expect:
var c = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
c.parse("2.5K"); // 2500
c.parse("1000000"); // 1000000
c.parse("1,000,000"); // 1 (stops at the comma)
c.parse("$1000000"); // ParseException
Localizing dates and times
Instead of writing a pattern, let the locale choose one. These factories use the default locale. Append withLocale(locale) to pick another:
| Factory | Formats |
|---|---|
DateTimeFormatter.ofLocalizedDate(FormatStyle dateStyle) | dates |
DateTimeFormatter.ofLocalizedTime(FormatStyle timeStyle) | times |
DateTimeFormatter.ofLocalizedDateTime(FormatStyle style) | both, one style |
DateTimeFormatter.ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle) | both, two styles |
FormatStyle has the values SHORT, MEDIUM, LONG and FULL:
| Style | US | ITALY |
|---|---|---|
SHORT | 3/7/26 | 07/03/26 |
MEDIUM | Mar 7, 2026 | 7 mar 2026 |
LONG | March 7, 2026 | 7 marzo 2026 |
FULL | Saturday, March 7, 2026 | sabato 7 marzo 2026 |
var dt = LocalDateTime.of(2026, 3, 7, 18, 5, 9);
var f = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT);
f.withLocale(Locale.US).format(dt); // 3/7/26, 6:05 PM
f.withLocale(Locale.ITALY).format(dt); // 07/03/26, 18:05
The same type-compatibility rules as custom patterns apply. Two of them catch people out:
- A localized time formatter on a
LocalDatethrows aDateTimeException. - The
LONGandFULLtime styles include a time zone, so using them on aLocalDateTimethrows aDateTimeException. They need aZonedDateTime.
Locale.Category
The default locale has two parts that can be set separately:
Locale.Category | Controls |
|---|---|
DISPLAY | how locale-related names are shown, e.g. getDisplayLanguage() printing Spanish or español |
FORMAT | how numbers, currencies and dates are formatted |
var spain = Locale.of("es", "ES");
Locale.setDefault(Locale.US);
// $1.23, Spanish both categories en_US
Locale.setDefault(Locale.Category.DISPLAY, spain);
// $1.23, español names in Spanish, formats still US
Locale.setDefault(Locale.Category.FORMAT, spain);
// 1,23 €, español both Spanish
Locale.setDefault(Locale.US);
// $1.23, Spanish the one-argument version resets BOTH
What's current
Locale.of(Java 19) replaced the deprecatedLocaleconstructors.Locale.BuilderandforLanguageTagremain current.- The old COMPAT locale data was removed in Java 23, so all formats come from CLDR, and output for some locales differs slightly between JDK versions.
Exam traps from this article
A complete example
A global ticket shop that formats the same values for six locales. It creates locales in every current way, formats numbers, currencies and percentages, shows how parsing depends on the locale, prints compact numbers in both styles, formats dates in all four styles, and switches Locale.Category values one at a time. Non-breaking spaces are shown as ~, and narrow ones as ^.
import java.text.NumberFormat;
import java.text.NumberFormat.Style;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.List;
import java.util.Locale;
import java.util.Locale.Category;
public class Solution {
// Make non-breaking spaces visible: U+00A0 as '~', the narrow U+202F as '^'
static String show(String s) {
return s.replace('\u00a0', '~').replace('\u202f', '^');
}
public static void main(String[] args) throws ParseException {
Locale.setDefault(Locale.US); // a known starting point for the demo
System.out.println("1) creating locales");
Locale built = new Locale.Builder().setRegion("JP").setLanguage("ja").build();
System.out.println(" " + Locale.GERMAN + " " + Locale.GERMANY + " " + Locale.of("it")
+ " " + Locale.of("es", "MX") + " " + built + " " + Locale.forLanguageTag("fr-CA"));
System.out.println(" " + Locale.of("es", "MX").getDisplayCountry() + " / "
+ Locale.of("es", "MX").getDisplayCountry(Locale.of("es")));
System.out.println("2) the same values in different locales");
double price = 48.5, rate = 0.8025, big = 1_234_567.891;
for (Locale l : List.of(Locale.US, Locale.UK, Locale.GERMANY, Locale.ITALY, Locale.JAPAN, Locale.CANADA_FRENCH)) {
System.out.printf(" %-6s number %-15s currency %-10s percent %s%n", l,
show(NumberFormat.getInstance(l).format(big)),
show(NumberFormat.getCurrencyInstance(l).format(price)),
show(NumberFormat.getPercentInstance(l).format(rate)));
}
NumberFormat whole = NumberFormat.getIntegerInstance(Locale.US);
System.out.println(" integer instance: 2.5 -> " + whole.format(2.5) + ", 3.5 -> " + whole.format(3.5)
+ ", 3.51 -> " + whole.format(3.51));
System.out.println("3) parsing depends on the locale");
String text = "40.45";
System.out.println(" \"" + text + "\" US -> " + NumberFormat.getInstance(Locale.US).parse(text)
+ ", FRANCE -> " + NumberFormat.getInstance(Locale.FRANCE).parse(text)
+ ", GERMANY -> " + NumberFormat.getInstance(Locale.GERMANY).parse(text));
double income = (Double) NumberFormat.getCurrencyInstance(Locale.US).parse("$92,807.99");
System.out.println(" currency \"$92,807.99\" -> " + income);
System.out.println("4) compact numbers");
for (Locale l : List.of(Locale.US, Locale.GERMANY)) {
for (Style style : Style.values()) {
NumberFormat c = NumberFormat.getCompactNumberInstance(l, style);
System.out.printf(" %-5s %-5s %s | %s | %s | %s%n", l, style, show(c.format(7_123_456)),
show(c.format(314_900_000)), show(c.format(1_550_000_000L)), show(c.format(950)));
}
}
NumberFormat shortUs = NumberFormat.getCompactNumberInstance(Locale.US, Style.SHORT);
System.out.println(" parse \"2.5K\" -> " + shortUs.parse("2.5K") + ", parse \"1,000,000\" -> "
+ shortUs.parse("1,000,000"));
System.out.println("5) localized date/time styles");
LocalDateTime concert = LocalDateTime.of(2026, 3, 7, 18, 5, 9);
for (FormatStyle fs : FormatStyle.values()) {
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate(fs);
System.out.printf(" %-6s US: %-25s IT: %s%n", fs, f.format(concert), f.withLocale(Locale.ITALY).format(concert));
}
DateTimeFormatter shortBoth = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT);
String usTime = shortBoth.format(concert);
System.out.println(" SHORT,SHORT US: " + show(usTime) + " IT: " + shortBoth.withLocale(Locale.ITALY).format(concert));
System.out.println(" equals \"3/7/26, 6:05 PM\"? " + usTime.equals("3/7/26, 6:05 PM"));
try {
DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL).format(concert);
} catch (RuntimeException e) {
System.out.println(" FULL time of a LocalDateTime -> " + e.getClass().getSimpleName());
}
System.out.println(" FULL time of a ZonedDateTime -> " + show(DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL)
.format(concert.atZone(ZoneId.of("Europe/Rome")))));
System.out.println("6) Locale.Category");
Locale spain = Locale.of("es", "ES");
printBoth(spain); // both categories en_US
Locale.setDefault(Category.DISPLAY, spain);
printBoth(spain); // names in Spanish, numbers US
Locale.setDefault(Category.FORMAT, spain);
printBoth(spain); // both Spanish
Locale.setDefault(Locale.US); // resets BOTH categories
printBoth(spain);
}
static void printBoth(Locale spain) {
System.out.println(" " + show(NumberFormat.getCurrencyInstance().format(1.23)) + ", "
+ spain.getDisplayLanguage() + " [DISPLAY=" + Locale.getDefault(Category.DISPLAY)
+ ", FORMAT=" + Locale.getDefault(Category.FORMAT) + "]");
}
}
Output:
1) creating locales
de de_DE it es_MX ja_JP fr_CA
Mexico / México
2) the same values in different locales
en_US number 1,234,567.891 currency $48.50 percent 80%
en_GB number 1,234,567.891 currency £48.50 percent 80%
de_DE number 1.234.567,891 currency 48,50~€ percent 80~%
it_IT number 1.234.567,891 currency 48,50~€ percent 80%
ja_JP number 1,234,567.891 currency ¥48 percent 80%
fr_CA number 1~234~567,891 currency 48,50~$ percent 80~%
integer instance: 2.5 -> 2, 3.5 -> 4, 3.51 -> 4
3) parsing depends on the locale
"40.45" US -> 40.45, FRANCE -> 40, GERMANY -> 4045
currency "$92,807.99" -> 92807.99
4) compact numbers
en_US SHORT 7M | 315M | 2B | 950
en_US LONG 7 million | 315 million | 2 billion | 950
de_DE SHORT 7~Mio. | 315~Mio. | 2~Mrd. | 950
de_DE LONG 7 Millionen | 315 Millionen | 2 Milliarden | 950
parse "2.5K" -> 2500, parse "1,000,000" -> 1
5) localized date/time styles
FULL US: Saturday, March 7, 2026 IT: sabato 7 marzo 2026
LONG US: March 7, 2026 IT: 7 marzo 2026
MEDIUM US: Mar 7, 2026 IT: 7 mar 2026
SHORT US: 3/7/26 IT: 07/03/26
SHORT,SHORT US: 3/7/26, 6:05^PM IT: 07/03/26, 18:05
equals "3/7/26, 6:05 PM"? false
FULL time of a LocalDateTime -> DateTimeException
FULL time of a ZonedDateTime -> 6:05:09^PM Central European Standard Time
6) Locale.Category
$1.23, Spanish [DISPLAY=en_US, FORMAT=en_US]
$1.23, español [DISPLAY=es_ES, FORMAT=en_US]
1,23~€, español [DISPLAY=es_ES, FORMAT=es_ES]
$1.23, Spanish [DISPLAY=en_US, FORMAT=en_US]
Points to notice:
- The yen amount has no decimals, and 48.5 rounded to
¥48(HALF_EVEN). - The same string
"40.45"parsed as40.45,40and4045in three locales, without a single exception. 1,550,000,000became2B. Compact formats round to whole units.- The US
SHORT,SHORTtime contained a narrow no-break space (^), so comparing it with a typed space failed. FULLtime needed a zone. It threw for theLocalDateTimeand worked for theZonedDateTime.- The last
Locale.setDefault(Locale.US)reset both categories. - The output is identical on JDK 21 and JDK 25 for these locales.
Common questions
Is NumberFormat thread-safe?
No. Create one per use, or per thread. Don't share one through a static field. DateTimeFormatter, by contrast, is immutable and safe to share.
How do I get a currency code like EUR?
Use Currency.getInstance(Locale.GERMANY).getCurrencyCode(), which gives EUR. You can also set a currency on a formatter with setCurrency.
Should my program call Locale.setDefault?
Rarely. Production code should pass explicit locales or use the user's default. The exam uses setDefault to make outputs predictable.
Summary
- A locale is
languageorlanguage_COUNTRY. Create one with constants,Locale.of,Locale.BuilderorforLanguageTag. The constructors are deprecated. NumberFormatfactories (getInstance,getCurrencyInstance,getPercentInstance,getIntegerInstance,getCompactNumberInstance) format and parse for a locale.parsethrowsParseException.CompactNumberFormatgivesSHORT(7M) orLONG(7 million) forms, rounded to whole units.ofLocalizedDate,ofLocalizedTimeandofLocalizedDateTimewithFormatStyle, pluswithLocale, localize dates.Locale.Category.DISPLAYandFORMATcan be set separately.
Practice quiz
Test yourself with the locales quiz: 10 exam-style questions with explanations.
Previous: Java Formatting: DecimalFormat, DateTimeFormatter Patterns and String.format (OCP 21)
Next: Java Resource Bundles: Properties Files, Lookup Order, MessageFormat and Properties (OCP 21)
Related reading
- Java Formatting: DecimalFormat, DateTimeFormatter Patterns and String.format (OCP 21)
- Java try-with-resources: AutoCloseable, Closing Order and Suppressed Exceptions (OCP 21)
- Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)
- Java Common Exception Classes: Runtime, Checked and Error Types on the Exam (OCP 21)
- Java Exceptions: Checked vs Unchecked, the Throwable Hierarchy and Overriding Rules (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.