Formatting dates and numbers
A value and the text a person reads are two things. A date is a value of lesson 110 and a formatted date is a string, and the bridge is DateTimeFormatter for dates and NumberFormat for numbers. Both take a Locale, which is the part a program forgets and a user notices.
DateTimeFormatter patterns
A pattern is a string of letters where each letter means a field: d the day, MMMM the month name, yyyy the year and HH the hour on a 24-hour clock:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class DateFormats {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2026, 3, 5);
System.out.println("iso: " + date);
System.out.println("pattern: " + date.format(DateTimeFormatter.ofPattern("d MMMM yyyy")));
System.out.println("de: " + date.format(DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.GERMAN)));
System.out.println("day/month:" + date.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
System.out.println("parsed: " + LocalDate.parse("05/03/2026", DateTimeFormatter.ofPattern("dd/MM/yyyy")));
LocalDateTime moment = LocalDateTime.of(2026, 11, 20, 14, 5, 9);
System.out.println("date time: " + moment.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
System.out.println("iso time: " + moment.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}
}
javac -Xlint:all DateFormats.java
java DateFormats
iso: 2026-03-05
pattern: 5 March 2026
de: 5 März 2026
day/month:05/03/2026
parsed: 2026-03-05
date time: 2026-11-20 14:05:09
iso time: 2026-11-20T14:05:09
The same date in two locales
The two middle lines are the same pattern with two locales, and the month name differs because German has its own. The default locale of the JVM decides what a formatter without one does, and that default is a property of the machine, which is the same trap as the default charset of lesson 109.
The parse is the inverse and it throws DateTimeParseException for a text that does not match, which is a DateTimeException and therefore unchecked. A program that reads a date from a user catches it, and a program that reads its own ISO output can let it out: the format is known and a mismatch is a bug.
NumberFormat
A number has the same problem in a sharper form, because the decimal separator and the group separator are the opposite way round in half of Europe. The program prints one value in two locales and then formats it as a percent, a currency and an integer:
import java.text.NumberFormat;
import java.util.Locale;
public class Numbers {
public static void main(String[] args) throws Exception {
double value = 1234.5;
NumberFormat en = NumberFormat.getInstance(Locale.US);
NumberFormat de = NumberFormat.getInstance(Locale.GERMANY);
System.out.println("us: " + en.format(value));
System.out.println("de: " + de.format(value));
System.out.println("us percent: " + NumberFormat.getPercentInstance(Locale.US).format(0.125));
System.out.println("de currency: " + NumberFormat.getCurrencyInstance(Locale.GERMANY).format(value));
System.out.println("us currency: " + NumberFormat.getCurrencyInstance(Locale.US).format(value));
System.out.println("integer: " + NumberFormat.getIntegerInstance(Locale.US).format(1234.9));
System.out.println("parsed: " + NumberFormat.getInstance(Locale.GERMANY).parse("1.234,5"));
}
}
javac -Xlint:all Numbers.java
java Numbers
us: 1,234.5
de: 1.234,5
us percent: 12%
de currency: 1.234,50 €
us currency: $1,234.50
integer: 1,235
parsed: 1234.5
The first two lines are one number and one value, and a program that reads the European form with the American parser gets 1.234 and stops, or throws. The percent rounds 12.5% to 12% because the default of the formatter is the half-even rounding of the next section. The integer formatter rounds 1234.9 up to 1,235, and the parse at the end returns a number that prints in the neutral form to be readable.
Rounding money
A double cannot hold 0.1 exactly, and the sum of 0.1 and 0.2 is the last line of the program. BigDecimal holds the decimal digits, and its rounding is explicit:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;
public class Money {
public static void main(String[] args) {
BigDecimal price = new BigDecimal("12.345");
System.out.println("half up: " + price.setScale(2, RoundingMode.HALF_UP));
System.out.println("half even: " + price.setScale(2, RoundingMode.HALF_EVEN));
System.out.println("floor: " + price.setScale(2, RoundingMode.FLOOR));
NumberFormat money = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println("formatted: " + money.format(new BigDecimal("1234.5")));
System.out.println("exact: " + new BigDecimal("0.1").add(new BigDecimal("0.2")));
System.out.println("double: " + (0.1 + 0.2));
}
}
javac -Xlint:all Money.java
java Money
half up: 12.35
half even: 12.34
floor: 12.34
formatted: $1,234.50
exact: 0.3
double: 0.30000000000000004
Three rounding modes on one value: HALF_UP moves the five away from zero, HALF_EVEN moves it to the even digit and FLOOR always goes down. A shop uses the mode its country's rules name, and the difference between the first two is a cent per contested invoice. The last two lines are the reason all of this is BigDecimal and not double.
Rules for formatting
Pass a Locale to every formatter, and decide which one: the user's for a screen, a fixed one for a file or a protocol. Store and exchange the ISO forms, which are unambiguous, and format for a person only at the edge. Round money with a mode and a scale that the rules of the business name, and keep the values in a type that holds decimals. A formatter is immutable and can be a constant, which also keeps the pattern in one place instead of scattered through the code.
The date in a log line is the case for a fixed pattern and a fixed zone, because a reader has to compare two lines from two machines; the date on a page is the case for the user's locale and zone. One program often needs both, and the two formatters are two constants.
Exercises
- Print the same date with the patterns yyyy-MM-dd, dd.MM.yyyy and EEEE d MMMM.
- Format 0.5 as a percent in two locales and explain the rounding.
- Round 2.675 to two places with HALF_UP and HALF_EVEN.
- Parse a date in the German pattern and print it in the ISO form.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a Locale decide in a formatter?
Answer
The names, the separators and the order of the parts
The month names and the decimal separator are properties of the language and the country.
-
Which class formats a number with a group separator?
Answer
NumberFormat
NumberFormat is the factory and the abstraction, and its format method does the work.
-
Why is money kept in BigDecimal?
Answer
It holds the decimal digits exactly, and the rounding is explicit
The sum of 0.1 and 0.2 is the demonstration that a binary double cannot hold decimals.
-
What does this program print?
import java.text.NumberFormat; import java.util.Locale; public class Q1 { public static void main(String[] args) { System.out.println(NumberFormat.getInstance(Locale.US).format(1234567.891)); } }Answer
1,234,567.891
The American locale groups by three with a comma and uses a dot for the decimals.
-
What does a pattern letter
Mmean?Answer
The month, as a number or a name depending on how many letters there are
One M is the number, two the two-digit number and four the name of the month.
-
Why store a date in the ISO form in a file?
Answer
It is unambiguous, and every program can read it without a locale
The ISO form is the interchange form, and the local form is for a person.
-
What is the difference between HALF_UP and HALF_EVEN on 12.345?
Answer
HALF_UP gives 12.35 and HALF_EVEN gives 12.34
The even rule sends the tie to the even digit, which is four here.
-
What does this program print?
import java.math.BigDecimal; import java.math.RoundingMode; public class Q2 { public static void main(String[] args) { BigDecimal value = new BigDecimal("2.675"); System.out.println(value.setScale(2, RoundingMode.HALF_UP)); System.out.println(value.setScale(1, RoundingMode.DOWN)); } }Answer
2.68 / 2.6
The exact decimal 2.675 rounds up to 2.68, and DOWN keeps one digit as it is.
-
What does
LocalDate.parsethrow for a text that does not match the pattern?Answer
DateTimeParseException, an unchecked exception
The date and time classes use unchecked exceptions for a text that does not fit.
-
Why does the German currency format not work as input for a US parser?
Answer
The separators and the currency symbol differ between the locales
A parser built for one locale reads the other form wrongly or refuses it.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev