Explain Codes LogoExplain Codes Logo

Add leading zeroes to a number in Java?

java
format-specifiers
string-format
number-formatting
Nikita BarsukovbyNikita Barsukov·Jan 28, 2025
TLDR

To add a leading zero to a number in Java, you can use the String.format() method with a "%0Nd" format specifier. Here, N represents the total length of the formatted string:

String paddedNum = String.format("%03d", 5);

Following the above code, the variable paddedNum will store the string "005", demonstrating a quick and clean way to produce a zero-padded output.

Format specifier explained

The String.format() method coupled with format specifiers works wonders when you have to display numbers in a fixed-width format.

Dissecting the format specifier %0Nd

  • %: Initiation of a format specifier.
  • 0: Padding to be done with zeroes (not spaces).
  • N: The length of the resulting string (including the number and the zeroes).
  • d: Denotes the use of an integer in decimal format.

Other formatting techniques

String.format() while being direct and efficient, isn't the only approach at your disposal. You can opt for other methods depending on your specific formatting requirements or API constraints.

Using DecimalFormat

The DecimalFormat class from the java.text package is an excellent tool for number formatting:

DecimalFormat df = new DecimalFormat("0000"); String paddedNum = df.format(9); // ".00" + "9" = "0009", a perfect magic trick!

Apache Commons Lang StringUtils to the rescue

Use the leftPad method from the Apache Commons Lang's StringUtils for string padding:

String paddedNum = StringUtils.leftPad("123", 5, '0'); // "123" goes "l33t" with "00123"

This method is particularly useful when you are dealing not with numeric primitives, but with strings that represent numbers.

printf for console-based formatting

For console output related dynamic formatting:

System.out.printf("%04d", 9); // voila, console says "0009"

printf leverages the same format specifiers as String.format() - a go-to-method for quick, formatted console outputs.

Be aware: common pitfalls & essential advice

Remember, with great power comes great responsibility. While leading zero-padding in Java can be straightforward, certain scenarios require due diligence to avoid stumbling into potential pitfalls.

Mind the size

Ensure the size of the number - no truncation occurs if it exceeds the specified width (N). This could disrupt fixed-width layout designs.

Dealing with Negative Numbers

Note: Negative numbers are padded with zeroes before the negative sign:

String.format("%03d", -7); // You get "-007", not Bond but still has a ring to it, no?

Non-numeric Padded Strings

Beware when padding non-numeric strings with String.format(). You might get unexpected results or errors!