How to pad a number with leading zeros
Short answer
The %05d pattern prints the number 5 characters wide, padded with zeros:
void main() {
IO.println(String.format("%05d", 42));
IO.println("%03d".formatted(7));
}Output:
00042
007An order number
Leading zeros are often used in document numbers:
void main() {
for (int id : new int[] {1, 25, 310}) {
IO.println("INV-%04d".formatted(id));
}
}Output:
INV-0001
INV-0025
INV-0310Time
Hours and minutes are usually printed with two digits:
void main() {
int totalSeconds = 3725;
int hours = totalSeconds / 3600;
int minutes = totalSeconds % 3600 / 60;
int seconds = totalSeconds % 60;
IO.println("%02d:%02d:%02d".formatted(hours, minutes, seconds));
}Output:
01:02:05A string of digits
If the value is already a string, pad it with repeat():
void main() {
String code = "815";
IO.println("0".repeat(Math.max(0, 6 - code.length())) + code);
}Output:
000815Common mistake
Storing a number with leading zeros in an int. A number has no use for zeros, so they disappear when parsed. Keep postal codes, phone numbers and codes as strings:
void main() {
int zip = Integer.parseInt("01067");
IO.println(zip);
}Output:
1067Functions used in this recipe
- String.format() — Builds a string from a template with placeholders such as %s and %d.
- String.repeat() — Repeats a string the given number of times.
- String.formatted() — Uses the string itself as a template and fills it in — a shorter form of String.format().