Java Formatting: DecimalFormat, DateTimeFormatter Patterns and String.format (OCP 21)
Formatting values for the OCP 21 exam: DecimalFormat patterns with # and 0, rounding and parsing, predefined ISO DateTimeFormatter constants, custom date/time pattern letters, which types support which letters, escaping literal text, parsing dates, and a String.format recap.
kvi5hnuCode Sprout team member7 min readOn this page
toString() gives you a representation of a value: 5678.9049, 2026-03-07T18:05:09. Users want $5,678.90 and Saturday, March 7. Java has three formatting tools:
| Tool | Package | For |
|---|---|---|
String.format / formatted | java.lang | quick printf-style messages (covered in article 17) |
NumberFormat / DecimalFormat | java.text | numbers with grouping, fixed decimals, currency, percent |
DateTimeFormatter | java.time.format | dates and times |
This article covers patterns you write yourself. The next article lets the locale pick the format for you.
Formatting numbers with DecimalFormat
NumberFormat is an abstract class with format(long) and format(double) methods. One concrete subclass, DecimalFormat, takes a pattern. For the exam you need two pattern symbols:
| Symbol | Meaning |
|---|---|
# | a digit, omitted if there's no digit for that position |
0 | a digit, printed as 0 if there's no digit for that position |
, | grouping separator, placed where you write it in the pattern |
. | decimal separator |
% | multiply by 100 and show a percent sign |
double total = 5678.9049;
new DecimalFormat("#,###.##").format(total); // 5,678.9 (# drops the trailing 0)
new DecimalFormat("000,000.000").format(total); // 005,678.905 (0 pads both sides)
new DecimalFormat("#,##0").format(total); // 5,679 (rounded, no decimals)
new DecimalFormat("Total: $#,##0.00").format(total); // Total: $5,678.90 (other characters are literal)
new DecimalFormat("0.0%").format(total); // 567890.5%
Things to watch:
- The number of
#s to the left of the decimal point doesn't limit the output.#and###,###,###both print every integer digit. To the right, the pattern sets the maximum number of decimals (#) or the exact number (0). - Rounding is
HALF_EVEN("banker's rounding"), not the half-up rounding you learned at school.new DecimalFormat("0").format(2.5)is2, whileformat(3.5)is4.0.125formats as0.12with"#.##"(an exact tie, soHALF_EVENgoes to the even digit 2). Binary floating point adds surprises too:1.005is really stored as 1.00499999…, so"#.##"prints1, not1.01. DecimalFormattakes its symbols (decimal point, grouping character) from the default locale. On a German machine,#,##0.00prints5.678,90. For stable output, pass the symbols explicitly:new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.US)).
Parsing goes the other way. parse(String) returns a Number and throws the checked ParseException when the text doesn't start with a number. It stops quietly at the first character it can't use:
NumberFormat money = new DecimalFormat("#,##0.00");
money.parse("1,234.5"); // 1234.5
money.parse("12kg"); // 12 (stops at "k")
money.parse("kg12"); // ParseException
There's a second concrete NumberFormat subclass, CompactNumberFormat (1.2K, 3 million). It's created through the locale API, which the next article covers.
Formatting dates and times with DateTimeFormatter
Predefined ISO formatters
LocalDate date = LocalDate.of(2026, 3, 7);
LocalTime time = LocalTime.of(18, 5, 9);
LocalDateTime when = LocalDateTime.of(date, time);
date.format(DateTimeFormatter.ISO_LOCAL_DATE); // 2026-03-07
time.format(DateTimeFormatter.ISO_LOCAL_TIME); // 18:05:09
when.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); // 2026-03-07T18:05:09
date.format(DateTimeFormatter.BASIC_ISO_DATE); // 20260307
date.format(DateTimeFormatter.ISO_LOCAL_TIME); // UnsupportedTemporalTypeException
A formatter that needs fields the value doesn't have fails at runtime. UnsupportedTemporalTypeException is a subclass of DateTimeException, which is unchecked.
Custom patterns with ofPattern
var f = DateTimeFormatter.ofPattern("MMMM d, yyyy 'at' hh:mm a");
when.format(f); // March 7, 2026 at 06:05 PM
f.format(when); // the same: both directions work

Case matters. M is month and m is minute. H is the 0–23 hour and h is the 1–12 hour, which you'll usually want to pair with a. A memory aid: the uppercase letter is the bigger unit.
The count of letters matters too:
| Pattern | Output for 7 March 2026 |
|---|---|
M, MM, MMM, MMMM | 3, 03, Mar, March |
d, dd | 7, 07 |
yy, yyyy | 26, 2026 |
E/EEE, EEEE | Sat, Saturday |
h:m:s vs hh:mm:ss for 18:05 | 6:5:9 vs 06:05:09 |
Match the letters to the type. A LocalDate has no hours, a LocalTime has no month, and only a ZonedDateTime has a zone. Formatting hh from a LocalDate, or z from a LocalDateTime, compiles but throws a DateTimeException when format runs.
Literal text
Pattern letters are A–Z and a–z, so any word you type in a pattern is read as a pattern too:
| Pattern | Result |
|---|---|
'Invoice date:' d MMM yyyy 'at' HH:mm | Invoice date: 7 Mar 2026 at 18:05. Single quotes make text literal. |
'Party''s at' h a | Party's at 6 PM. Two single quotes print one quote. |
Time hh:mm | IllegalArgumentException from ofPattern, because T isn't a pattern letter |
'Due hh:mm | IllegalArgumentException, because the quote is never closed |
Due hh:mm | no error: D, u and e are letters (day of year, year, day of week), so it prints 6620267 06:05 |
Punctuation and spaces outside quotes, like / - : , _, are printed as-is.
Pattern errors are detected when ofPattern builds the formatter. Type mismatches are detected when format runs. Both throw unchecked exceptions.
Parsing with a pattern
var dmy = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate.parse("25/12/2026", dmy); // 2026-12-25
LocalDate.parse("2026-12-25", dmy); // DateTimeParseException (unchecked)
LocalTime.parse("6:15 PM", DateTimeFormatter.ofPattern("h:mm a", Locale.US)); // 18:15
String.format recap
From article 17: String.format(pattern, args) and "pattern".formatted(args) (Java 15+) use % specifiers such as %s (any object), %d (integers), %f (floating point, 6 decimals by default), %.2f, %,d (grouping) and %n (line separator). Width and flags pad the output: %8.2f, %-6s, %05d. A specifier that doesn't match its argument throws an IllegalFormatException subclass at runtime. Pass a Locale as the first argument for locale-independent output.
What's current
- Java 23 added strict parsing to
NumberFormat(setStrict(true)):parse("12abc")then throwsParseExceptioninstead of returning 12. It's off by default and isn't on 1Z0-830. DateTimeFormatteris the current date formatter.SimpleDateFormatis legacy and not thread-safe. String templates, previewed in Java 21 and 22, were withdrawn in Java 23, soString.formatandformattedremain the way to format text.
Exam traps from this article
A complete example
An invoice formatter. It applies several DecimalFormat patterns to one amount, shows HALF_EVEN rounding and lenient parsing, formats a date and time with ISO constants and custom patterns, escapes literal text, demonstrates every runtime mistake from this article, and parses text back into dates and times.
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.function.Supplier;
public class Solution {
// US symbols so the output is the same on every machine (see the localization article)
static final DecimalFormatSymbols US = DecimalFormatSymbols.getInstance(Locale.US);
static String num(String pattern, double value) {
return new DecimalFormat(pattern, US).format(value);
}
static DateTimeFormatter fmt(String pattern) {
return DateTimeFormatter.ofPattern(pattern, Locale.US);
}
static void tryPattern(String label, Supplier<Object> code) {
try {
System.out.println(" " + label + " -> \"" + code.get() + "\"");
} catch (RuntimeException e) {
System.out.println(" " + label + " -> " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) throws ParseException {
double total = 5678.9049;
System.out.println("1) DecimalFormat: # omits, 0 pads");
for (String p : new String[] {"#,###.##", "000,000.000", "#,##0", "Total: $#,##0.00", "0.0%"}) {
System.out.printf(" %-18s %s%n", p, num(p, total));
}
System.out.println(" HALF_EVEN rounding with \"0\": 2.5 -> " + num("0", 2.5)
+ ", 3.5 -> " + num("0", 3.5));
NumberFormat money = new DecimalFormat("#,##0.00", US);
System.out.println(" parse \"1,234.5\" -> " + money.parse("1,234.5")
+ ", parse \"12kg\" -> " + money.parse("12kg"));
try {
money.parse("kg12");
} catch (ParseException e) {
System.out.println(" parse \"kg12\" -> ParseException at offset " + e.getErrorOffset());
}
LocalDate date = LocalDate.of(2026, 3, 7);
LocalTime time = LocalTime.of(18, 5, 9);
LocalDateTime when = LocalDateTime.of(date, time);
System.out.println("2) predefined ISO formatters");
System.out.println(" " + date.format(DateTimeFormatter.ISO_LOCAL_DATE)
+ " | " + time.format(DateTimeFormatter.ISO_LOCAL_TIME)
+ " | " + when.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
System.out.println("3) custom patterns (letter case and count matter)");
for (String p : new String[] {"M/d/yy", "MM/dd/yyyy", "MMM d, yyyy", "EEEE, MMMM d",
"hh:mm a", "HH:mm:ss", "h:m:s", "D"}) {
System.out.printf(" %-14s %s%n", p, when.format(fmt(p)));
}
System.out.println("4) literal text in single quotes");
System.out.println(" " + when.format(fmt("'Invoice date:' d MMM yyyy 'at' HH:mm")));
System.out.println(" " + when.format(fmt("'Party''s at' h a")));
System.out.println("5) both format() directions are equivalent");
DateTimeFormatter dmy = fmt("dd/MM/yyyy");
System.out.println(" " + date.format(dmy) + " == " + dmy.format(date));
System.out.println("6) mistakes");
tryPattern("month of a LocalTime", () -> time.format(fmt("MM")));
tryPattern("hour of a LocalDate", () -> date.format(fmt("hh")));
tryPattern("zone of a LocalDateTime", () -> when.format(fmt("HH:mm z")));
tryPattern("unquoted 'Due'", () -> when.format(fmt("Due hh:mm"))); // D, u, e are pattern letters!
tryPattern("unquoted 'Time'", () -> fmt("Time hh:mm")); // T is not
tryPattern("unclosed quote", () -> fmt("'Due hh:mm"));
tryPattern("parse wrong shape", () -> LocalDate.parse("2026-12-25", dmy));
ZonedDateTime zoned = ZonedDateTime.of(when, ZoneId.of("America/New_York"));
System.out.println(" zone on a ZonedDateTime -> " + zoned.format(fmt("HH:mm z (Z)")));
System.out.println("7) parsing with a pattern");
System.out.println(" " + LocalDate.parse("25/12/2026", dmy)
+ " | " + LocalTime.parse("6:15 PM", fmt("h:mm a")));
}
}
Output:
1) DecimalFormat: # omits, 0 pads
#,###.## 5,678.9
000,000.000 005,678.905
#,##0 5,679
Total: $#,##0.00 Total: $5,678.90
0.0% 567890.5%
HALF_EVEN rounding with "0": 2.5 -> 2, 3.5 -> 4
parse "1,234.5" -> 1234.5, parse "12kg" -> 12
parse "kg12" -> ParseException at offset 0
2) predefined ISO formatters
2026-03-07 | 18:05:09 | 2026-03-07T18:05:09
3) custom patterns (letter case and count matter)
M/d/yy 3/7/26
MM/dd/yyyy 03/07/2026
MMM d, yyyy Mar 7, 2026
EEEE, MMMM d Saturday, March 7
hh:mm a 06:05 PM
HH:mm:ss 18:05:09
h:m:s 6:5:9
D 66
4) literal text in single quotes
Invoice date: 7 Mar 2026 at 18:05
Party's at 6 PM
5) both format() directions are equivalent
07/03/2026 == 07/03/2026
6) mistakes
month of a LocalTime -> UnsupportedTemporalTypeException
hour of a LocalDate -> UnsupportedTemporalTypeException
zone of a LocalDateTime -> DateTimeException
unquoted 'Due' -> "6620267 06:05"
unquoted 'Time' -> IllegalArgumentException
unclosed quote -> IllegalArgumentException
parse wrong shape -> DateTimeParseException
zone on a ZonedDateTime -> 18:05 EST (-0500)
7) parsing with a pattern
2026-12-25 | 18:15
Points to notice:
#,###.##printed5,678.9, dropping the trailing zero, whileTotal: $#,##0.00kept two decimals and printed the literal text around them.2.5rounded down to2and3.5rounded up to4: HALF_EVEN picks the even neighbour.parse("12kg")returned12without complaint, but"kg12"threwParseExceptionat offset 0.Dprinted66, the day of the year, not the day of the month.- The unquoted
Dueproduced garbage instead of an error, whileTimefailed inofPattern. - Only the
ZonedDateTimecould printzandZ.
Common questions
Should I use DecimalFormat or String.format?
String.format("%,.2f", x) is shorter for simple cases. DecimalFormat gives full control over patterns, parses text back into numbers, and the exam tests it directly.
Are formatters thread-safe?
DateTimeFormatter is immutable and thread-safe, so store it in a static final field. DecimalFormat and SimpleDateFormat are not: create one per thread, or use ThreadLocal.
What's the difference between y and u?
y is the year of the era, and u is the proleptic year, which can be negative. They're the same for modern dates. Strict parsing prefers u.
Summary
DecimalFormat:#omits and0pads.,groups and%multiplies by 100. Rounding is HALF_EVEN, andparsethrows the checkedParseException.DateTimeFormatterhas ISO constants andofPatternwith case- and count-sensitive letters:y M d E D H h m s a z Z VV.- Letters must match the type's fields, or
formatthrows aDateTimeException. - Put literal text in single quotes, and write
''for a quote. Unknown letters or an unclosed quote makeofPatternthrowIllegalArgumentException. LocalDate.parse(text, formatter)reverses formatting, and throws the uncheckedDateTimeParseException.
Practice quiz
Test yourself with the formatting quiz: 10 exam-style questions with explanations.
Previous: Java try-with-resources: AutoCloseable, Closing Order and Suppressed Exceptions (OCP 21)
Next: Java Locales: Localizing Numbers, Currency, Percentages, Compact Numbers and Dates (OCP 21)
Related reading
- 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)
- Java Collectors: joining, toMap, groupingBy, partitioningBy and teeing (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.