How do you left pad an int with zeros when converting to a String in java? I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).

In Java, you can left pad an integer with zeros when converting it to a string by using the String.format() method with the %0Nd format specifier, where N is the minimum width of the output string and d indicates that the argument is an integer. Here's how you can achieve this:

java

public class Main {
    public static void main(String[] args) {
        int number = 1;
        String paddedNumber = String.format("%04d", number); // %04d means 4 digits, zero-padded
        System.out.println(paddedNumber); // Output: 0001
        
        int anotherNumber = 123;
        String paddedAnotherNumber = String.format("%04d", anotherNumber);
        System.out.println(paddedAnotherNumber); // Output: 0123
    }
}

In this example, %04d specifies that the integer should be formatted with a minimum width of 4 characters, padded with zeros if necessary.

Keep in mind that the String.format() method returns a formatted string, so you need to store the result in a variable or directly use it as needed.

Comments