# 2 Examples to Add Zeros at the Beginning of a Number in Java (Padding)

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 finance domain. There are so many legacy systems out there which expect the input of certain length, and if your input is shorter than specified length, you got to add zeros at the beginning of number to make them off right length. Java has 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 powerful String.format() method or it's 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 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 number 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 at 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 meaning of those characters :
1. % denotes that it's a formatting instruction
2. 0 is a flag which says pad with zero
3. 4 denotes length of formatted String, this will ensure that right number of zero should be added
4. d is for decimal which means 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 meta data to get a feel of it. For example you can change the length to pad more or less 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 e.g. an Android app available in different countries and in 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 add zeros at front of various input you can see that it adds right number of zeros smartly depending upon number of digits in input.

## 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 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. Following code will add leading zeros to the input number, if 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 formatter with four zeros which means it will always return a four digit numeric String with zeros in front. So if your input consist just 1 digit say 9, it will return 0009 as show in 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 on 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

```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 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

System.out.printf("4 digit number padded with zero to make 6 digit : %06d %n", 4001);

// just replace %d with %x, as shown below

// 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
DecimalFormat df = new DecimalFormat("000000");
System.out.println("Number formatted using DecimalFormat" + df.format(23));
}

}

Output:
4 digit number padded with zero to make 6 digit : 004001
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 system, which accept input of 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 concept 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 usage and being comfortable with this method helps a lot. As I said, formatting is 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.

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass

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.

2. 1. 3. 