How to left pad Integer with zeroes in java

Left pad Integer with zeroes in java

In this post, we will see how to left pad Integer with zeroes in java.
There are multiple ways to left pad Integer with zeroes in java.

Using String’s format() method

You can use String‘s format() method to add leading zeroes to Integer in java. This is simplest and elegant solution to left pad Integer with zeroes in java.
Let’s say you want to add 3 leading zeroes to Integer of lenght 2, so you need to provide following format:

Add leading zeroes to Integer on left

Here is an example:

Output:

00012

Using DecimalFormat

You can also use DecimalFormat‘s format() method to left pad Integer with zeroes. You need to pass format with all 0 of total length to do this.
For example:

Here is an example:

Output:

Formatted Integer with 3 leading zeroes: 00012

Using NumberFormat

You can use NumberFormat’s format() method with setMaximumIntegerDigits() and setMinimumIntegerDigits() to add leading zeroes to Integer in java.
Here is an example:

Output:

Formatted Integer with 3 leading zeroes: 00012

Using apache common lang3

You can use Apache common’s StringUtils class to pad integer with leading zeroes.
Here is the dependency which you need to add for Apache common lang3 in pom.xml.

Here, we are using StringUtils.leftPad() method. Here are the overloaded version of leftPad.

Here is an example:

Output:

Formatted Integer with 3 leading zeroes: 00012

Using Guava library

You can also use Guava’s Strings class to left pad String.
Here is the dependency which you need to add for guava in pom.xml.

Here, we are using Strings.padStart() method. The overloaded version of padStart() are:

Here is an example:

Output:

Formatted Integer with 3 leading zeroes: 00012

Using System.out.printf

If you just want to print left pad Integer with zeroes in java, you can use System.out.printf().
Here is an example:

Output:

Formatted Integer with 3 leading zeroes: 00012

Using StringBuilder

You can write your own solution using for loop and StringBuffer rather than using any library method.
Here is an example:

Output:

Formatted Integer with 3 leading zeroes: 00012

Using String’s substring() method

You can use for loop and substring() method to left pad integer with zeroes in java.

First create a String of total length of all 0s and then use substring() to extract required left pad zeroes and concatenate original String to it.
Here is an example:

Output:

Formatted Integer with 3 leading zeroes: 00012

That’s all about how to left pad integer with zeroes in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *