How to add Zeros at the Beginning of a Number in Java [Left Padding Examples]

How do you left pad an integer value with zeroes in Java when converting to a string? This is a common requirement if you are working in the finance domain. There are so many legacy systems out there that expect the input of a certain length, and if your input is shorter than the specified length, you got to add zeros at the beginning of the number to make them off the right length. Java has a rich API and thankfully neither converting an integer to String is difficult nor formatting String to add leading zeros. In fact, there are multiple ways to add zeros at the start of a number or numeric string, you can either use the powerful String.format() method or its close cousin printf() method, or you can go back to DecimalFormat class if you are still working in JDK 4. Formatting, in general, is a very useful concept and as a Java developer, you must have a good understanding of that.

Earlier we have learned about formatting floating-point numbers in Java and that knowledge is going to help a lot. There we have learned about using both String.format() and DecimalFormat to create floating-point numbers up to two, three, or four decimal places.

If you have read that article then you are already familiar with tricky formatting instructions we pass to format() method e.g. "%07d", in this article we will learn how to left pad an integer value in Java by adding zeros in front of the number.




Using format() method of String to pad Numeric String

Let's take a hypothetical example of a legacy system which accept a terminal id which can be anything between 1 to 9999, but requirement is that input must always be 4 character long e.g. you cannot pass "9",  "99" or "999" instead you need to pass "0009", "0099" or "0999"

So you need to either write a routine who is smart enough to add right numbers of zeros in front, as it varies depending upon input, or you can simply use String.format() method to do your job. Here is the code, which will always create a 4 character long numeric String, and it will add either 1, 2, or 3 zeros to make final String 4 character long.
int number = 9;        
String str = String.format("%04d", 9);  // 0009      
System.out.printf("original number %d, numeric string with padding : %s",
                     9, str); 

Now let's see what this code is doing. All the magic is in format String, let's understand the meaning of those characters :
  1. % denotes that it's a formatting instruction
  2. 0 is a flag that says pad with zero
  3. 4 denotes the length of formatted String, this will ensure that the right number of zero should be added
  4. d is for decimal which means the next argument should be an integral value e.g. byte, char, short, int, or long.

You can play with this code by changing each of these metadata to get a feel of it. For example, you can change the length to pad more or fewer zeros e.g. %06d will always create a left padded numeric String of six-digit

By the way, while using String.format() method you must remember that formatting is locale-specific. This version of format() method will use default locale, returned by Locale.getDefaultLocale() method,  which is mostly Locale.US, but if you are writing an application where internationalization is used like an Android app available in different countries and in a different language, you should consider using overloaded format method, which takes Locale as parameter i.e. format(Locale locale, String format, Object... args). 


This way you can control how your formatted numeric String will look like depending upon the locale. Here is a screenshot of how this method adds zeros in front of various inputs you can see that it adds the right number of zeros smartly depending upon the number of digits in input.


Adding leading zero on numbers in Java with example

Using DecimalFormat to Pad Integers with Zero in Java

Our last example is good enough to create a left padded numeric String but unfortunately, it was only available from Java 1.5 onwards. What do you do if your application is still running on Java 1.4, of course, you will cry for the update to at least Java 1.5 until you are tired of asking it. No need to be disappointed, Java 1.4 has DecimalFormat to help you out. The following code will add leading zeros to the input number if a number has less than 4 digits.
 DecimalFormat df = new DecimalFormat("0000");
 String c = df.format(9);   // 0009
 String a = df.format(99);  // 0099
 String b = df.format(999); // 0999
Here we have created a formatter with four zeros which means it will always return a four-digit numeric String with zeros in front. So if your input consists of just 1 digit say 9, it will return 0009 as shown in the first example, if your input contains 2 digits, it will return 0099 and if your input contains 3 digits it will add just one leading zero at the start. If you pass a four-digit number it will not add anything. You can try these examples or let me know if you have any trouble executing them.


How to add zeros at the beginning of a number in Java

Here is our Java program to demonstrate how you can left pad a number with leading zeros in Java without using any third-party library like Apache Commons or Google Guava. There are two main ways to add zeros at the start of an integer number in Java, first by using format() method of String class, and second by using format() method of DecimalFormat class

String.format() is my preferred solution because of it's extensive usage but it is only available from Java 1.5, so if your application has stuck in JDK 1.4, you cannot use it. For those warriors, I have shared how you pad numbers using DecimalFormat

By the way padding is a part for formatting and if you are familiar with formatting String in Java, it would be very easy to understand. In first example we have used String.format() to convert 220 to a 8 digit long numeric String, "%08d" will create 8 digit long String. 

You can also add leading zeros in hexadecimal numbers by using "x" instead of "d", as shown in next example. This example is the same we discussed in our DecimalFormat section, it creates numeric String of length 6 with zeros in front.
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Formatter;
 
/**
* Java program to pad leading zeros into numbers e.g. integer and long in Java
* This method returns a String which contains padded zero.
*
* @author Javin Paul
*/
public class PaddingNumbersInJava{
 
    public static void main(String args[]) {
 
        int quantity = 220;
 
        // %08 means total length of number would be 8
        // if number is of 3 digits, rest of them will
        // be padded by leading zeros.
        String padded = String.format("%08d", quantity);
        System.out.println("Number padded with leading zero : " + padded);
 
        System.out.printf("4 digit number padded with zero to make 6 digit :
                     %06d %n", 4001);
 
        // You can also display hexadecimal number padded by zero
        // just replace %d with %x, as shown below
        System.out.printf("2 digit hexadecimal number padded with zero : 
                      %06x %n", 0xBE);
 
        // Another way to left pad a number is by using DecimalFormat class
        // Below format will make String 6 digit long
        // if number is less than 6 digit long, it will be padded by
        // leading zero.
        DecimalFormat df = new DecimalFormat("000000");
        System.out.println("Number formatted using DecimalFormat" 
                            + df.format(23));
    }
 
}
 
 
Output:
Number padded with leading zero : 00000220
4 digit number padded with zero to make 6 digit : 004001
2 digit hexadecimal number padded with zero : 0000be
Number formatted using DecimalFormat : 000023

That's all on how to add zeros at the beginning of a number in Java. You need this kind of padding while working with financial systems and some legacy systems, which accept input of a certain length. Thanks to Java converting an integer to String is not a big task but formatting String is still tricky, hopefully by following these examples, you will get hold of one of the more useful concepts of formatting String in Java. 

By using these methods you can easily pad as many zeros as you like because String has no range in Java. By any chance, if you are stuck with Java 1.4 you can use DecimalFormat to do the job (second example) otherwise prefer String.format() method of Java 1.5 because it also has lots of other users and being comfortable with this method helps a lot. 

As I said, formatting is a very useful concept and you must master it. You will often find yourself formatting date and time or dealing with formatted numbers in Java. A good grasp of formatting instruction will help you a lot.


6 comments:

  1. isn't padding is just opposite of trimming? then if we can have a trim() method on String class, why not we can have pad() method as well? or may be left_pad() and right_pad() to apply padding on left or right side of String.

    ReplyDelete

  2. Thanks for giving good solution
    and for me DecimalFormat was just working and I think the reason was that I have set font in my project
    thanks a lot to you

    ReplyDelete
  3. title of this article says how-to-pad-numbers-with-leading-zeroes-in-Java,
    but all you show is how to add zeros to String. What about int when you parse from string to int?

    ReplyDelete
    Replies
    1. Adding leading zero on int will have no effect because 0 infront of number is ignored for any calculation. padding a display concept and when you display numbers, you need to convert them to string if you want to add leading zeros.

      Delete

Feel free to comment, ask questions if you have any doubt.