Format number leading zeros

In this example we will show how to format a number with leading zeros using variations in java, guava and apache commons. Often you deal with inputs that are stored as numbers that you want you want to display as a formatted string. A couple examples are social security number (SSN) or a phone number. You could argue whether or not the raw data is a string but when you display it you want it to look a format that is natural to a user. In each snippet below we defined the length of the value to be five and we will pass 123 to be formatted as '00123'.

Straight up Java

DecimalFormat

Using java's DecimalFormat we will format a integer with leading zeros by creating a pattern and then calling the DecimalFormat.format passing it in the value to format.

@Test
public void format_leading_zeros() {

    DecimalFormat df = new DecimalFormat("00000");

    assertEquals("00123", df.format(123));
}

String.format

Using java String.format method we will specify a format and then pass in the object to be formatted.

@Test
public void format_leading_zeros_string_format() {

    String leadingZero = String.format("%05d", 123);

    assertEquals("00123", leadingZero);
}

Google Guava

Using guava we will pad leading zeros to a decimal by calling the Strings.padStart utility method specifying the minimum value and the character to pad with.

@Test
public void format_leading_zeros_guava() {

    int asNumber = 123;

    String leadingZero = Strings.padStart(String.valueOf(asNumber), 5, '0');

    assertEquals("00123", leadingZero);
}

Apache Commons

Similar to the guava snippet above we will specify a min length and the value to pad with which will result in padding number with leading zeros.

@Test
public void format_leading_zeros_apache_commons() {

    int asNumber = 123;

    String leadingZero = StringUtils.leftPad(String.valueOf(asNumber), 5,
            "0");

    assertEquals("00123", leadingZero);
}