Number Formats in Java: NumberFormat, Compact Numbers, DecimalFormat and Currencies
Formatting and parsing numbers for people in any locale: NumberFormat factories, compact numbers like 1.5M, lenient versus strict parsing (Java 23), DecimalFormat patterns and rounding, DecimalFormatSymbols, and the Currency class with locale extensions for accounting style.
kvi5hnuCode Sprout team member12 min readOn this page
Article 71 showed that 123456.78 must be written 123.456,78 for a German reader and 123’456.78 for a Swiss one. The java.text package contains the classes that do this work: the abstract NumberFormat, its main implementation DecimalFormat, CompactNumberFormat for short forms like 1.5M, and DecimalFormatSymbols for the characters involved. java.util.Currency describes the money side. This article covers all of them, including the strict parsing mode added in Java 23.
The NumberFormat factories
Formatting a number for a locale takes three steps: choose the locale, ask a static factory of NumberFormat for a formatter, and call format (or parse).
NumberFormat f = NumberFormat.getCurrencyInstance(Locale.GERMANY);
String s = f.format(123456.78); // 123.456,78 €
| Factory | en-US | de-DE | fr-FR | ja-JP |
|---|---|---|---|---|
getNumberInstance (or getInstance) | 123,456.78 | 123.456,78 | 123 456,78 | 123,456.78 |
getCurrencyInstance | $123,456.78 | 123.456,78 € | 123 456,78 € | ¥123,457 |
getPercentInstance (0.256) | 26% | 26 % | 26 % | 26% |
getIntegerInstance | 123,457 | 123.457 | 123 457 | 123,457 |
getCompactNumberInstance (Java 12) | 123K | 123.457 | 123 k | 12万 |
Each factory also exists without a locale argument and then uses the FORMAT default. Notice details that you would never get right by hand: the euro sign after the number in German and French, the narrow no-break space (U+202F) used for grouping in French and the no-break space (U+00A0) before €, the yen amount rounded to whole yen because yen have no minor unit, and the full-width yen sign ¥ in Japanese.
The returned object is really a subclass, in practice a DecimalFormat or CompactNumberFormat. The factory methods are how you get the locale-correct configuration; you can then cast to DecimalFormat to fine-tune it.
Common settings on any NumberFormat:
setMinimumFractionDigits,setMaximumFractionDigits,setMinimumIntegerDigits,setMaximumIntegerDigits.setGroupingUsed(false)to suppress thousands separators.setRoundingMode(RoundingMode); the default isHALF_EVEN("banker's rounding"), sogetIntegerInstanceturns 2.5 into 2 and 3.5 into 4.setParseIntegerOnly(true)to stop parsing at the decimal separator.
Compact numbers
Dashboards and social media show 1.2K or 15 lakh instead of the full figure. NumberFormat.getCompactNumberInstance(locale, NumberFormat.Style.SHORT or LONG) (Java 12) gives the locale's abbreviations, taken from CLDR:
| Value | en-US SHORT | de-DE SHORT | ja-JP SHORT | hi-IN SHORT |
|---|---|---|---|---|
| 1,234 | 1K | 1.234 | 1,234 | 1 हज़ार |
| 1,500,000 | 2M | 2 Mio. | 150万 | 15 लाख |
| 2,000,000,000 | 2B | 2 Mrd. | 20億 | 2 अ॰ |
The LONG style spells out the unit (2 million, 2 Millionen). Several things in this table are worth noticing. German has no short form for thousands, so it prints the full number. Japanese groups by ten thousand (万) and Hindi by lakh (100,000) and crore. And by default no fraction digits are shown, so 1.5 million rounds to 2M; call setMaximumFractionDigits(1) to get 1.5M. Compact formatters can also parse: "1.5M" gives 1500000. Since Java 14 a CompactNumberFormat handles plural forms (1 million versus 2 millions in French) through CLDR plural rules.
Parsing numbers
parse(String) reads a number written in the formatter's locale and returns a Number, which is a Long if the value is integral and fits, otherwise a Double (or a BigDecimal after setParseBigDecimal(true) on a DecimalFormat). You then call doubleValue(), longValue() and so on; a Number is not unboxed automatically.
NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);
de.parse("1.234,5"); // Double 1234.5
de.parse("42"); // Long 42
By default parsing is lenient:
- Leading characters that are not part of the number cause a
ParseException, so strip whitespace first (text.strip()). - Trailing characters are silently ignored:
"12abc"parses as 12. That is useful for pulling a number out of"12 kg", dangerous for validating a form field. - Grouping separators are accepted anywhere, so
"1.23,5"is fine in lenient German mode.
To see how much was consumed, use parse(String, ParsePosition): after parsing "12,5 kg" the position is 4, and you can check that it equals the length of the input. getErrorIndex() reports where a failure happened.
Strict parsing (Java 23)
Java 23 added setStrict(boolean) and isStrict() to NumberFormat, implemented by DecimalFormat, CompactNumberFormat and ChoiceFormat. For any other subclass the inherited implementation throws UnsupportedOperationException. Parsing remains lenient unless you switch it on. In strict mode the whole text must be a correctly formatted number:
| Input (de-DE, strict) | Result | Why |
|---|---|---|
1.234,5 | 1234.5 | matches the conventions exactly |
12abc | rejected | extra characters |
1.23,5 | rejected | the group size is not 3 |
1234,5 | rejected | grouping is enabled, so 4 digits without a separator break the group size |
Strict mode also requires the prefix and suffix (the $ of a US currency format, the % of a percent format) and rejects grouping symbols after the decimal separator. If users may type numbers without thousands separators, call setGroupingUsed(false), which in strict mode in turn rejects any grouping symbol, or accept both forms by trying two formatters.
DecimalFormat patterns
When the locale defaults are not what you need, construct a DecimalFormat from a pattern, or apply one with applyPattern. The pattern describes the positive part and, after an optional ;, the negative part:

| Symbol | Meaning |
|---|---|
0 | a digit, always shown (padded with zero) |
# | a digit, shown only if not a leading or trailing zero |
. | decimal separator placeholder |
, | grouping separator placeholder; the number of digits between the last , and the end of the integer part is the group size |
E | separates mantissa and exponent in scientific notation |
; | separates the positive and negative subpatterns |
- | minus sign placeholder |
%, ‰ (U+2030) | multiply by 100 or 1000 and show the sign |
¤ (U+00A4) | currency symbol; ¤¤ is the ISO code |
' | quotes special characters; '' is a literal quote |
Some examples with US symbols:
| Pattern | Input | Output |
|---|---|---|
0.00 | -3.14159 | -3.14 |
#,##0.### | 1234567.891 | 1,234,567.891 |
000000 | 42 | 000042 |
0.00;(0.00) | -3.5 | (3.50) |
#,##0.00 ¤¤ | 1234.5 | 1,234.50 USD |
0.###E0 | 123456 | 1.235E5 |
##0.##E0 | 123456 | 123.46E3 (engineering notation: exponent a multiple of 3) |
#.#‰ | 0.0256 | 25.6‰ |
'#'# | 7 | #7 |
The negative subpattern only contributes its prefix and suffix; the digit layout always comes from the positive part. Pattern characters are placeholders: , and . print as the locale's symbols, so the same pattern prints 1.234,50 with German symbols. toPattern() shows the pattern behind a factory formatter; for German currency it is #,##0.00 ¤ with a no-break space.
Some properties cannot be expressed in a pattern and have setters only: setDecimalSeparatorAlwaysShown, setMultiplier, setGroupingSize (a single size, which is why Indian 1,23,456 grouping is not possible), setParseBigDecimal, and setRoundingMode.
DecimalFormatSymbols
The actual characters come from a DecimalFormatSymbols object: getDecimalSeparator, getGroupingSeparator, getMonetaryDecimalSeparator, getMonetaryGroupingSeparator (Java 15), getMinusSign, getPercent, getPerMill, getExponentSeparator, getInfinity (∞), getNaN (NaN), getZeroDigit, getCurrencySymbol and getInternationalCurrencySymbol. Each has a setter.
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.GERMANY);
symbols.setGroupingSeparator('\'');
symbols.setDecimalSeparator('.');
var f = new DecimalFormat("#,##0.00", symbols); // 123'456.78
getZeroDigit matters for scripts with their own digits: in ar-EG, zero is U+0660 and the number prints as ١٢٣٬٤٥٦٫٧٨. The other nine digits are the next nine code points. A Unicode extension such as -u-nu-latn or -u-nu-thai in the locale selects the numbering system explicitly.
Currencies
getCurrencyInstance(locale) picks the currency of the locale's region. That is wrong when the currency does not follow the reader: an invoice for an American customer may contain both dollars and euros, and it should use US conventions for both. Keep the locale and change the currency:
NumberFormat f = NumberFormat.getCurrencyInstance(Locale.US);
f.setCurrency(Currency.getInstance("EUR"));
f.format(1234.5); // €1,234.50
java.util.Currency represents an ISO 4217 currency:
| Currency | Code | Numeric | Fraction digits |
|---|---|---|---|
| US dollar | USD | 840 | 2 |
| Euro | EUR | 978 | 2 |
| Japanese yen | JPY | 392 | 0 |
| Indian rupee | INR | 356 | 2 |
| Swiss franc | CHF | 756 | 2 |
| British pound | GBP | 826 | 2 |
| Chinese yuan | CNY | 156 | 2 |
Obtain one with Currency.getInstance(code) or Currency.getInstance(locale) (the currency of the locale's country; it throws IllegalArgumentException for a locale without a supported country). Query it with getCurrencyCode, getNumericCode/getNumericCodeAsString, getDefaultFractionDigits, getSymbol(locale) and getDisplayName(locale). Currency.getAvailableCurrencies() returns a set, and Java 25 added Currency.availableCurrencies() returning a stream.
Locale extensions for currency formats
Two Unicode extensions are useful here (article 71 explains extensions):
cf-accountselects the accounting style, which shows negative amounts in parentheses:en-US-u-cf-accountformats -12.5 as($12.50)instead of-$12.50.cu-xxxoverrides the currency:de-CH-u-cu-eurformats Swiss-style but in euros (EUR 12.50).
Beyond these, the JDK has no money arithmetic. For amounts with currency, conversion and rounding rules, the JSR 354 Money and Currency API (reference implementation Moneta) is the common choice; it is a separate library.
Scanner, Formatter and String.format
Locale-aware number handling is not limited to NumberFormat:
Scanner.useLocale(Locale.GERMANY)makesnextDouble()read3,75andnextInt()read1.000.String.format(locale, "%,.2f", x),Formatter, andPrintStream.printf(locale, ...)use the locale's separators. Without a locale argument they use the FORMAT default, so machine-readable output should passLocale.ROOT.Double.parseDouble,Integer.parseIntandtoStringare locale-independent and always use.and ASCII digits. They are the right tools for files and protocols.
The program
The demo prints the factories for six locales, compact numbers, lenient and strict parsing, a set of DecimalFormat patterns, rounding cases, custom and Arabic symbols, currencies, and locale extensions. Non-breaking spaces are shown as <NBSP> and narrow ones as <NNBSP>.
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.*;
import java.util.*;
public class Solution {
static final List<Locale> LOCALES = List.of(Locale.US, Locale.GERMANY,
Locale.of("de", "CH"), Locale.FRANCE, Locale.JAPAN, Locale.forLanguageTag("hi-IN"));
public static void main(String[] args) throws ParseException {
double amount = 123456.78;
System.out.println("== The three classic factories ==");
for (Locale loc : LOCALES) {
System.out.printf("%-6s %-14s %-18s %s%n", loc.toLanguageTag(),
v(NumberFormat.getNumberInstance(loc).format(amount)),
v(NumberFormat.getCurrencyInstance(loc).format(amount)),
v(NumberFormat.getPercentInstance(loc).format(0.256)));
}
System.out.println("integer instance rounds half-even: "
+ NumberFormat.getIntegerInstance(Locale.US).format(2.5) + " "
+ NumberFormat.getIntegerInstance(Locale.US).format(3.5));
System.out.println("\n== Compact numbers ==");
long[] values = {999, 1_234, 56_789, 1_500_000, 2_000_000_000L};
for (Locale loc : List.of(Locale.US, Locale.GERMANY, Locale.JAPAN, Locale.forLanguageTag("hi-IN"))) {
NumberFormat shortF = NumberFormat.getCompactNumberInstance(loc, NumberFormat.Style.SHORT);
NumberFormat longF = NumberFormat.getCompactNumberInstance(loc, NumberFormat.Style.LONG);
StringJoiner sj = new StringJoiner(" | ");
for (long n : values) sj.add(v(shortF.format(n)));
System.out.println(loc.toLanguageTag() + " SHORT: " + sj);
System.out.println(loc.toLanguageTag() + " LONG : " + v(longF.format(1_500_000)));
}
NumberFormat oneDecimal = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
oneDecimal.setMaximumFractionDigits(1);
System.out.println("with 1 fraction digit: " + oneDecimal.format(1_234) + ", " + oneDecimal.format(1_500_000));
System.out.println("parse \"1.5M\": " + oneDecimal.parse("1.5M"));
System.out.println("\n== Parsing ==");
NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);
System.out.println("parse \"1.234,5\" (de) -> " + de.parse("1.234,5")
+ " (" + de.parse("1.234,5").getClass().getSimpleName() + ")");
System.out.println("parse \"42\" (de) -> " + de.parse("42")
+ " (" + de.parse("42").getClass().getSimpleName() + ")");
System.out.println("lenient \"12abc\" -> " + de.parse("12abc"));
try {
de.parse(" 12");
} catch (ParseException e) {
System.out.println("leading space -> ParseException at " + e.getErrorOffset());
}
ParsePosition pos = new ParsePosition(0);
Number partial = de.parse("12,5 kg", pos);
System.out.println("ParsePosition: " + partial + " stopped at index " + pos.getIndex());
NumberFormat strict = NumberFormat.getNumberInstance(Locale.GERMANY);
strict.setStrict(true);
for (String s : List.of("1.234,5", "12abc", "1.23,5", "1234,5")) {
try {
System.out.println("strict \"" + s + "\" -> " + strict.parse(s));
} catch (ParseException e) {
System.out.println("strict \"" + s + "\" -> rejected");
}
}
DecimalFormat big = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
big.setParseBigDecimal(true);
System.out.println("BigDecimal parse: " + big.parse("12345678901234567890.123456789"));
System.out.println("\n== DecimalFormat patterns ==");
DecimalFormatSymbols us = DecimalFormatSymbols.getInstance(Locale.US);
String[][] patterns = {
{"0.00", "-3.14159"}, {"#,##0.###", "1234567.891"}, {"000000", "42"},
{"0.00;(0.00)", "-3.5"}, {"#,##0.00 ¤", "1234.5"}, {"#,##0.00 ¤¤", "1234.5"},
{"0.###E0", "123456"}, {"##0.##E0", "123456"}, {"#%", "0.256"}, {"#.#‰", "0.0256"},
{"'#'#", "7"}, {"0 o''clock", "5"}};
for (String[] p : patterns) {
DecimalFormat df = new DecimalFormat(p[0], us);
System.out.printf("%-14s %-14s %s%n", p[0], p[1], df.format(Double.parseDouble(p[1])));
}
DecimalFormat money = new DecimalFormat("#,##0.00", us);
System.out.println("HALF_EVEN default: 0.125 -> " + money.format(0.125)
+ ", 0.135 -> " + money.format(0.135));
money.setRoundingMode(RoundingMode.HALF_UP);
System.out.println("HALF_UP on BigDecimal 0.125 -> " + money.format(new BigDecimal("0.125")));
System.out.println("double 1.005 HALF_UP -> " + money.format(1.005)
+ " (1.005 is really " + new BigDecimal(1.005).toPlainString().substring(0, 22) + "...)");
System.out.println("toPattern of de-DE currency: "
+ ((DecimalFormat) NumberFormat.getCurrencyInstance(Locale.GERMANY)).toPattern().replace("\u00a0", "<NBSP>"));
System.out.println("\n== DecimalFormatSymbols ==");
DecimalFormatSymbols custom = DecimalFormatSymbols.getInstance(Locale.GERMANY);
custom.setGroupingSeparator('\'');
custom.setDecimalSeparator('.');
DecimalFormat swissStyle = new DecimalFormat("#,##0.00", custom);
System.out.println("custom separators: " + swissStyle.format(amount));
DecimalFormatSymbols arabic = DecimalFormatSymbols.getInstance(Locale.forLanguageTag("ar-EG"));
System.out.println("ar-EG zero digit U+" + Integer.toHexString(arabic.getZeroDigit()).toUpperCase()
+ ", formatted: " + new DecimalFormat("#,##0.00", arabic).format(amount));
System.out.println("NaN / infinity in en-US: " + NumberFormat.getInstance(Locale.US).format(Double.NaN)
+ " " + NumberFormat.getInstance(Locale.US).format(Double.POSITIVE_INFINITY));
System.out.println("\n== Currencies ==");
NumberFormat invoice = NumberFormat.getCurrencyInstance(Locale.US);
for (String code : List.of("USD", "EUR", "JPY", "INR", "CHF")) {
Currency c = Currency.getInstance(code);
invoice.setCurrency(c);
System.out.printf("%s digits=%d num=%s symbol(US)=%s name=%s -> %s%n", code,
c.getDefaultFractionDigits(), c.getNumericCodeAsString(),
c.getSymbol(Locale.US), c.getDisplayName(Locale.US), invoice.format(1234.5));
}
Currency yen = Currency.getInstance("JPY");
invoice.setCurrency(yen);
invoice.setMinimumFractionDigits(yen.getDefaultFractionDigits());
invoice.setMaximumFractionDigits(yen.getDefaultFractionDigits());
System.out.println("JPY with fraction digits fixed -> " + invoice.format(1234.5));
System.out.println("Currency of de-CH: " + Currency.getInstance(Locale.of("de", "CH")));
System.out.println("Euro symbol in de-DE vs en-US: " + Currency.getInstance("EUR").getSymbol(Locale.GERMANY)
+ " / " + Currency.getInstance("EUR").getSymbol(Locale.US));
System.out.println("Accounting style (u-cf-account): "
+ NumberFormat.getCurrencyInstance(Locale.forLanguageTag("en-US-u-cf-account")).format(-12.5)
+ " vs " + NumberFormat.getCurrencyInstance(Locale.US).format(-12.5));
System.out.println("Currency override (u-cu-eur): "
+ v(NumberFormat.getCurrencyInstance(Locale.forLanguageTag("de-CH-u-cu-eur")).format(12.5)));
System.out.println("availableCurrencies() count > 200: " + (Currency.availableCurrencies().count() > 200));
System.out.println("\n== Scanner and Formatter ==");
Scanner sc = new Scanner("3,75 1.000").useLocale(Locale.GERMANY);
System.out.println("Scanner(de): " + sc.nextDouble() + " " + sc.nextInt());
System.out.println("String.format(de): " + String.format(Locale.GERMANY, "%,.2f", amount));
System.out.println("formatted(ROOT-like): " + String.format(Locale.ROOT, "%,.2f", amount));
}
static String v(String s) {
return s.replace("\u202f", "<NNBSP>").replace("\u00a0", "<NBSP>");
}
}
== The three classic factories ==
en-US 123,456.78 $123,456.78 26%
de-DE 123.456,78 123.456,78<NBSP>€ 26<NBSP>%
de-CH 123’456.78 CHF<NBSP>123’456.78 26%
fr-FR 123<NNBSP>456,78 123<NNBSP>456,78<NBSP>€ 26<NBSP>%
ja-JP 123,456.78 ¥123,457 26%
hi-IN 123,456.78 ₹123,456.78 26%
integer instance rounds half-even: 2 4
== Compact numbers ==
en-US SHORT: 999 | 1K | 57K | 2M | 2B
en-US LONG : 2 million
de-DE SHORT: 999 | 1.234 | 56.789 | 2<NBSP>Mio. | 2<NBSP>Mrd.
de-DE LONG : 2 Millionen
ja-JP SHORT: 999 | 1,234 | 6万 | 150万 | 20億
ja-JP LONG : 150万
hi-IN SHORT: 999 | 1<NBSP>हज़ार | 57<NBSP>हज़ार | 15<NBSP>लाख | 2<NBSP>अ॰
hi-IN LONG : 15 लाख
with 1 fraction digit: 1.2K, 1.5M
parse "1.5M": 1500000
== Parsing ==
parse "1.234,5" (de) -> 1234.5 (Double)
parse "42" (de) -> 42 (Long)
lenient "12abc" -> 12
leading space -> ParseException at 0
ParsePosition: 12.5 stopped at index 4
strict "1.234,5" -> 1234.5
strict "12abc" -> rejected
strict "1.23,5" -> rejected
strict "1234,5" -> rejected
BigDecimal parse: 12345678901234567890.123456789
== DecimalFormat patterns ==
0.00 -3.14159 -3.14
#,##0.### 1234567.891 1,234,567.891
000000 42 000042
0.00;(0.00) -3.5 (3.50)
#,##0.00 ¤ 1234.5 1,234.50 $
#,##0.00 ¤¤ 1234.5 1,234.50 USD
0.###E0 123456 1.235E5
##0.##E0 123456 123.46E3
#% 0.256 26%
#.#‰ 0.0256 25.6‰
'#'# 7 #7
0 o''clock 5 5 o'clock
HALF_EVEN default: 0.125 -> 0.12, 0.135 -> 0.14
HALF_UP on BigDecimal 0.125 -> 0.13
double 1.005 HALF_UP -> 1.00 (1.005 is really 1.00499999999999989341...)
toPattern of de-DE currency: #,##0.00<NBSP>¤
== DecimalFormatSymbols ==
custom separators: 123'456.78
ar-EG zero digit U+660, formatted: ١٢٣٬٤٥٦٫٧٨
NaN / infinity in en-US: NaN ∞
== Currencies ==
USD digits=2 num=840 symbol(US)=$ name=US Dollar -> $1,234.50
EUR digits=2 num=978 symbol(US)=€ name=Euro -> €1,234.50
JPY digits=0 num=392 symbol(US)=¥ name=Japanese Yen -> ¥1,234.50
INR digits=2 num=356 symbol(US)=₹ name=Indian Rupee -> ₹1,234.50
CHF digits=2 num=756 symbol(US)=CHF name=Swiss Franc -> CHF1,234.50
JPY with fraction digits fixed -> ¥1,234
Currency of de-CH: CHF
Euro symbol in de-DE vs en-US: € / €
Accounting style (u-cf-account): ($12.50) vs -$12.50
Currency override (u-cu-eur): EUR<NBSP>12.50
availableCurrencies() count > 200: true
== Scanner and Formatter ==
Scanner(de): 3.75 1000
String.format(de): 123.456,78
formatted(ROOT-like): 123,456.78
Common questions
How do I format money correctly?
Keep amounts in BigDecimal (or as long minor units), choose the currency explicitly, and format with NumberFormat.getCurrencyInstance(readerLocale) plus setCurrency(currency) and the currency's fraction digits. Never compute with double for money.
How do I parse user input like "1,234.50" safely?
Use a NumberFormat for the user's locale with setStrict(true) (Java 23) and setParseBigDecimal(true) on a DecimalFormat, and check that the whole string was consumed. In lenient mode, "12abc" parses as 12 without an error.
Why does Double.parseDouble("1,5") fail on a German machine?
Double.parseDouble and Integer.parseInt are locale-independent and always expect a dot. That's correct for files and protocols. For user input, use NumberFormat.getInstance(locale).parse(...).
Is String.format("%.2f", x) locale-sensitive?
Yes, it uses the FORMAT default locale, so it can print 3,14. Pass a locale (String.format(Locale.ROOT, "%.2f", x)) for machine-readable output.
How do I show Indian grouping such as 1,23,456?
DecimalFormat supports only one grouping size, so it can't. Use ICU4J's NumberFormat, or format the number yourself. Compact formats (getCompactNumberInstance for hi-IN or en-IN) do use lakh and crore.
Where do I get exchange rates?
Not from the JDK. Currency only describes currencies. Rates come from a bank or a service API, and JSR 354 (Moneta) provides an interface for conversion providers.
API reference
| Method | Purpose |
|---|---|
NumberFormat.getNumberInstance/getInstance/getIntegerInstance/getPercentInstance/getCurrencyInstance([locale]) | locale-specific formatters |
NumberFormat.getCompactNumberInstance([locale, style]) (12) | short forms like 1K, 2 Mio. |
format(long/double/Object), parse(String[, ParsePosition]) | format and parse |
setStrict(boolean), isStrict() (23) | strict parsing |
setMinimum/MaximumFraction/IntegerDigits, setGroupingUsed, setRoundingMode, setParseIntegerOnly | configuration |
new DecimalFormat(pattern[, symbols]), applyPattern, toPattern | patterns |
DecimalFormat.setParseBigDecimal, setGroupingSize, setMultiplier, setDecimalSeparatorAlwaysShown | settings outside the pattern |
DecimalFormatSymbols.getInstance(locale) and its getters/setters | separators, signs, digits |
Currency.getInstance(code or locale), getAvailableCurrencies(), availableCurrencies() (25) | currencies |
getCurrencyCode, getNumericCodeAsString (9), getDefaultFractionDigits, getSymbol(locale), getDisplayName(locale) | currency data |
NumberFormat.setCurrency(Currency) | change currency, keep locale |
Summary
- Get number formatters from the
NumberFormatfactories with an explicit locale; never build locale formats by hand. getCompactNumberInstanceproduces1.5M-style output with the locale's own units; set fraction digits if you want them.- Parsing returns a
Number(Long,Double, orBigDecimalon request). It is lenient by default and ignores trailing text; usesetStrict(true)(Java 23) or check theParsePositionwhen validating. DecimalFormatpatterns use0,#,,,.,E,;,%,‰and¤; the actual symbols come fromDecimalFormatSymbols.- Default rounding is
HALF_EVEN; format money asBigDecimalto avoid binary surprises. NumberFormatis not thread-safe.- Use
setCurrencyto show another currency with the reader's conventions, and fix the fraction digits. Locale extensionscf-accountandcu-xxxselect accounting style and currency.
Practice Questions
1. A web form uses NumberFormat.getNumberInstance(Locale.GERMANY).parse(input) and the input "12,5 Liter" is accepted as 12.5. Why, and how do you reject it?
Lenient parsing stops at the first character that cannot belong to the number and ignores the rest. Call setStrict(true) (Java 23 and later) so that extra characters cause a ParseException, or use parse(input, pos) and check that pos.getIndex() == input.length().
2. What is printed by new DecimalFormat("#,##0.00;(#)", DecimalFormatSymbols.getInstance(Locale.US)).format(-1234.5)?
(1,234.50). The negative subpattern supplies only the prefix ( and suffix ); its digit part (#) is ignored, and the digits, grouping and fraction digits come from the positive subpattern.
3. Why does NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT).format(1_500_000) print 2M?
Compact formatters show no fraction digits by default, and the default rounding mode HALF_EVEN rounds 1.5 to 2. Call setMaximumFractionDigits(1) to print 1.5M.
4. An American invoice must show an amount in yen. What is wrong with NumberFormat.getCurrencyInstance(Locale.JAPAN), and what should you do?
The Japanese formatter applies Japanese conventions, including the full-width ¥ symbol, which is not what an American reader expects for the rest of the document. Use getCurrencyInstance(Locale.US), call setCurrency(Currency.getInstance("JPY")), and set the minimum and maximum fraction digits to getDefaultFractionDigits() (0), because setCurrency keeps the two decimals of the dollar format.
5. A program writes CSV files with String.format("%.2f", price). Users in Germany report broken files. What happened?
String.format without a locale uses the FORMAT default locale, which in Germany uses a decimal comma: 12,50 instead of 12.50, which also collides with the comma separator of the CSV file. Use String.format(Locale.ROOT, "%.2f", price), or BigDecimal.toPlainString, for machine-readable output.
Previous: Locales in Java: Language Tags, Default Locales and Display Names
Next: Localized Dates, Collation and Unicode Normalization in Java
Related reading
- Locales in Java: Language Tags, Default Locales and Display Names
- Formatting and Parsing Dates in Java, and Converting Legacy Date and Calendar
- LocalTime, ZonedDateTime and Daylight Saving Time in Java
- LocalDate, Period and Temporal Adjusters in Java
- Instant and Duration in Java: Points and Spans on the Time Line

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.