Java
String Formatting
Programming
Leading Zero
Coding Tips

How to format a Java string with leading zero?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Use String.format("%05d", value) to pad an integer with leading zeros to a fixed width. The 0 flag tells the formatter to pad with zeros instead of spaces, and the number after it specifies the total width. For example, String.format("%05d", 42) produces "00042".

java
String result = String.format("%05d", 42);
System.out.println(result); // 00042

This is the standard approach in Java for invoice numbers, time components, file naming, and any situation where a fixed-width numeric string is required. The rest of this article covers the format specifier syntax in detail, alternative approaches with DecimalFormat and StringUtils, handling edge cases with negative numbers, and how to pad strings (not just integers) with leading characters.

The String.format Approach

Format Specifier Breakdown

The format specifier %05d consists of four parts:

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 value controls how many characters the result will be at minimum. If the number already has that many or more digits, no padding is added:

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)

The formatter never truncates. If the value is wider than the specified width, the full value is printed.

Dynamic Width

When the width needs to be 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

This helper method is worth creating when padding appears in multiple places across the codebase. It centralizes the format string and makes width changes trivial.

Formatting long Values

The same specifier works with long values:

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

Use d for both int and long. Java's formatter handles the promotion automatically.

Using DecimalFormat

DecimalFormat provides pattern-based numeric formatting and is part of java.text:

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

Each 0 in the pattern represents a required digit position. If the number has fewer digits, zeros fill the remaining positions from the left.

When to Use DecimalFormat Over String.format

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

Using printf for Console Output

When the padded value is only needed for printing, System.out.printf uses the same format syntax as String.format:

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

The %n at the end produces a platform-appropriate newline. This is convenient for logging and debugging but does not produce a String you can pass to other methods. If you need the string value elsewhere, use String.format.

Padding Strings (Not Just Numbers)

The %0Nd specifier only works with numeric types. If you need to pad a string with leading zeros (or any other character), Java does not have a single built-in method, but there are several clean approaches.

Using String.format with Right-Alignment and 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 replaces spaces with zeros. It works but fails if the original string contains spaces.

Using 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

This is the cleanest option when Apache Commons is already a dependency. It handles all edge cases and supports any padding character.

Using 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

This is dependency-free and readable. The Math.max(0, ...) guard prevents negative repeat counts when the input is already wider than the target.

Handling Negative Numbers

Negative values include the minus sign as part of the formatted 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

The sign character counts toward the total width. A width of 6 with a negative value leaves 5 positions for digits. This is usually the correct behavior for financial or accounting displays, but you should be aware of it when defining the width.

If you need the sign to appear after the zeros (unusual but sometimes required), you must handle it manually:

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

Practical Use Cases

File Naming with Sequential Numbers

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}

Zero-padded filenames sort correctly in file explorers and command-line listings because 0002 sorts before 0010 lexicographically.

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 and Reference Numbers

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

Common Pitfalls

Expecting an int to preserve leading zeros. Java integers are numeric values, not strings. int x = 00042 is just 42. Leading zeros in integer literals actually indicate octal notation (042 = 34 in decimal). Always format at the display boundary.

Formatting early and parsing back. Converting a padded string back to an integer 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. Do not round-trip through parseInt if you need the zeros.

Hardcoding format strings across the codebase. Scattering "%05d" in 20 different files means changing the width requires 20 edits. Extract it into a constant or utility method.

Confusing DecimalFormat pattern characters. In DecimalFormat, 0 means "required digit" and # means "optional digit." Using "#####" instead of "00000" will not add leading zeros because # suppresses them.

Using %0Ns instead of %0Nd. The zero-pad flag only works with numeric conversions (d, o, x). Using it with s (string) throws FormatFlagsConversionMismatchException.

Summary

  • String.format("%05d", value) is the standard way to add leading zeros to integers in Java.
  • The 0 flag enables zero-padding; the number after it sets the minimum width.
  • DecimalFormat is better for locale-aware or pattern-based numeric formatting.
  • For string padding, use StringUtils.leftPad, String.repeat (Java 11+), or the format-and-replace trick.
  • Negative numbers include the sign in the width count.
  • Leading zeros are a display concern. Keep values as numbers for computation and format to strings only at the output boundary.
  • Never use %0Ns (zero-pad with string conversion). Zero-padding is only valid with numeric format specifiers.

Course illustration
Course illustration

All Rights Reserved.