Left pad an integer with zeros in Java
This post will discuss how to left pad an integer with zeros in Java.
1. Using String.format() method
The String.format() method returns a formatted string using the specified format string. You can provide the '0' flag, which causes the output to be padded with leading zeros until the length of the string is equal to the desired field width. This is demonstrated below:
|
1 2 3 4 5 6 7 8 |
public class Main { public static void main(String[] args) { int intValue = 125; String s = String.format("%05d", intValue); System.out.println(s); } } |
Output:
00125
2. Using PrintStream#printf() method
Alternatively, if you need to write the padded output to the output stream, you can do so using the PrintStream#printf() method. It accepts a format string with the '0' flag, similar to the String.format() method.
|
1 2 3 4 5 6 7 |
public class Main { public static void main(String[] args) { int intValue = 1024; System.out.printf("%05d", intValue); } } |
Output:
01024
3. Using DecimalFormat.format() method
Another option is to create a DecimalFormat using a pattern consisting of all zeros. The number of zeros in the pattern string should be equal to the desired field width.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.text.DecimalFormat; public class Main { public static void main(String[] args) { int intValue = 111; DecimalFormat df = new DecimalFormat("00000"); String s = df.format(intValue); System.out.println(s); } } |
Output:
00111
4. Using Apache Commons Lang
You can also use the StringUtils.leftPad() method from Apache Commons Lang Library to pad an integer with leading zeros to a specific length.
|
1 2 3 4 5 6 7 8 9 10 11 |
import org.apache.commons.lang3.StringUtils; public class Main { public static void main(String[] args) { int intValue = 1; int size = 5; String s = StringUtils.leftPad(String.valueOf(intValue), size, '0'); System.out.println(s); } } |
Output:
00001
5. Using Guava
If you prefer Guava to Apache Commons Lang, you can use the padStart() method from the Strings class to get a left padded string as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
import com.google.common.base.Strings; public class Main { public static void main(String[] args) { int intValue = 125; int size = 4; String s = Strings.padStart(String.valueOf(intValue), size, '0'); System.out.println(s); } } |
Output:
0125
That’s all about left padding an integer with zeros in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)