Java
String Formatting
Programming
Leading Zero
Coding Tips

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".

java
String result = String.format("%05d", 42);
System.out.println(result); // 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

PartMeaning
%Starts the format specifier
0Use zero-padding instead of space-padding
5Minimum total width of the output
dFormat 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:

java
1System.out.println(String.format("%05d", 7));      // 00007
2System.out.println(String.format("%05d", 123));    // 00123
3System.out.println(String.format("%05d", 99999));  // 99999
4System.out.println(String.format("%05d", 100000)); // 100000 (exceeds width, no truncation)

Making the width configurable

Build the format string dynamically:

java
1public static String zeroPad(int value, int width) {
2    return String.format("%0" + width + "d", value);
3}
4
5System.out.println(zeroPad(42, 6));  // 000042
6System.out.println(zeroPad(42, 3));  // 042
7System.out.println(zeroPad(42, 2));  // 42

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:

java
long bigNumber = 123456789L;
System.out.println(String.format("%015d", bigNumber)); // 000000123456789

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:

java
1import java.text.DecimalFormat;
2
3DecimalFormat df = new DecimalFormat("00000");
4System.out.println(df.format(42));    // 00042
5System.out.println(df.format(123));   // 00123
6System.out.println(df.format(99999)); // 99999
ScenarioBetter choice
Simple fixed-width integer paddingString.format
Locale-aware formatting (grouping separators, decimal points)DecimalFormat
Pattern includes decimal places (e.g., "000.00")DecimalFormat
Format string is loaded from configurationDecimalFormat
Part of a larger formatted message with multiple placeholdersString.format
java
1// DecimalFormat with decimal places
2DecimalFormat df = new DecimalFormat("000.00");
3System.out.println(df.format(3.5));   // 003.50
4System.out.println(df.format(42.1));  // 042.10

Printing padded values with printf

System.out.printf uses the same syntax when you only need to print:

java
int value = 7;
System.out.printf("Order ID: %08d%n", value);
// Order ID: 00000007

%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

java
String input = "abc";
String padded = String.format("%10s", input).replace(' ', '0');
System.out.println(padded); // 0000000abc

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

java
1import org.apache.commons.lang3.StringUtils;
2
3String padded = StringUtils.leftPad("abc", 10, '0');
4System.out.println(padded); // 0000000abc
5
6String padded2 = StringUtils.leftPad("12345", 10, '0');
7System.out.println(padded2); // 0000012345

The cleanest option if Apache Commons is already a dependency. It handles the edge cases and accepts any padding character.

String.repeat (Java 11+)

java
1String input = "abc";
2int targetWidth = 10;
3String padded = "0".repeat(Math.max(0, targetWidth - input.length())) + input;
4System.out.println(padded); // 0000000abc

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

java
System.out.println(String.format("%06d", -42));   // -00042
System.out.println(String.format("%06d", -1234)); // -01234
System.out.println(String.format("%06d", -99999)); // -99999

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:

java
1int value = -42;
2String sign = value < 0 ? "-" : "";
3String padded = sign + String.format("%05d", Math.abs(value));
4System.out.println(padded); // -00042

Examples: file names, times and invoice numbers

Sequential file names. Zero-padded names sort correctly because 0002 sorts before 0010 lexicographically:

java
1for (int i = 1; i <= 100; i++) {
2    String filename = String.format("image_%04d.png", i);
3    // image_0001.png, image_0002.png, ..., image_0100.png
4}

Time display:

java
1int hours = 9;
2int minutes = 5;
3int seconds = 3;
4String time = String.format("%02d:%02d:%02d", hours, minutes, seconds);
5System.out.println(time); // 09:05:03

Invoice numbers:

java
int invoiceId = 1547;
String invoiceNumber = "INV-" + String.format("%08d", invoiceId);
System.out.println(invoiceNumber); // INV-00001547

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:

java
String padded = String.format("%05d", 42);   // "00042"
int parsed = Integer.parseInt(padded);        // 42

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.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data 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.

Practice algorithms