How to format a Java string or number with leading zeros
Codemia Knowledge Hub ·
Use String.format("%05d", value) to pad an integer with leading zeros to a fixed width. The 0 flag pads with zeros instead of spaces and the number after it sets the total width, so String.format("%05d", 42) produces "00042".
This is the standard approach for invoice numbers, time components, file names and anything else that needs a fixed-width numeric string.
How the %05d specifier works
| Part | Meaning |
% | Starts the format specifier |
0 | Use zero-padding instead of space-padding |
5 | Minimum total width of the output |
d | Format as a decimal integer |
The width is a minimum. If the number already has that many digits or more, no padding is added, and the formatter never truncates:
Making the width configurable
Build the format string dynamically:
A helper like this is useful when padding appears in several places, since it keeps the format string in one spot.
Padding long values
Use d for both int and long:
Padding with DecimalFormat
java.text.DecimalFormat uses patterns. Each 0 is a required digit position, and missing digits are filled with zeros from the left:
| Scenario | Better choice |
| Simple fixed-width integer padding | String.format |
| Locale-aware formatting (grouping separators, decimal points) | DecimalFormat |
Pattern includes decimal places (e.g., "000.00") | DecimalFormat |
| Format string is loaded from configuration | DecimalFormat |
| Part of a larger formatted message with multiple placeholders | String.format |
Printing padded values with printf
System.out.printf uses the same syntax when you only need to print:
%n produces a platform-appropriate newline. printf does not return a String, so use String.format if you need the value elsewhere.
Padding strings with leading zeros
%0Nd only works with numeric types. Java has no single built-in method for padding a string, but there are a few clean options.
String.format plus replace
This right-aligns the string in a 10-character field padded with spaces, then turns the spaces into zeros. It breaks if the original string contains spaces.
Apache Commons StringUtils.leftPad
The cleanest option if Apache Commons is already a dependency. It handles the edge cases and accepts any padding character.
String.repeat (Java 11+)
Dependency-free and readable. The Math.max(0, ...) guard prevents a negative repeat count when the input is already wider than the target.
Negative numbers count the sign in the width
A width of 6 with a negative value leaves 5 positions for digits. That is usually right for financial displays, but keep it in mind when choosing the width. If you want the digit count to exclude the sign, handle the sign yourself:
Examples: file names, times and invoice numbers
Sequential file names. Zero-padded names sort correctly because 0002 sorts before 0010 lexicographically:
Time display:
Invoice numbers:
Mistakes with leading zeros
Expecting an int to keep leading zeros. An integer is a number, not a string. Leading zeros in an integer literal actually mean octal (042 is 34 in decimal). Format at the display boundary.
Formatting early and parsing back. Parsing a padded string strips the zeros:
Keep the padded value as a String once formatted.
Hardcoding format strings everywhere. Scattering "%05d" across 20 files means 20 edits to change the width. Put it in a constant or utility method.
Using # in DecimalFormat. 0 means "required digit" and # means "optional digit", so "#####" adds no leading zeros.
Using %0Ns instead of %0Nd. The zero-pad flag only works with numeric conversions (d, o, x). With s it throws FormatFlagsConversionMismatchException.
Related reading
- How to format date and time in Android?
- How to format Joda-Time DateTime to only mm/dd/yyyy?
- How to format strings in Java
- How to free memory in Java?
- How to generate a ddl creation script with a modern Spring Boot Data JPA and Hibernate setup?
- How to generate a random permutation in Java
- How to generate a secure random alphanumeric string in Java efficiently?
- How to generate buildConfigField with String type
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.