Add leading zeroes to number in Java?

Add leading zeroes to number in Java?

To add leading zeroes to a number in Java, you can use String.format() or String.format() method. Here's how you can do it:

public class AddLeadingZeroes {
    public static void main(String[] args) {
        int number = 42;
        int width = 5; // The total width of the resulting string

        // Using String.format()
        String formattedNumber = String.format("%0" + width + "d", number);
        System.out.println("Using String.format(): " + formattedNumber);

        // Using String.format() with printf-style format
        formattedNumber = String.format("%05d", number);
        System.out.println("Using String.format() with printf-style format: " + formattedNumber);

        // Using String.format() with variable width
        width = 7;
        formattedNumber = String.format("%0" + width + "d", number);
        System.out.println("Using String.format() with variable width: " + formattedNumber);
    }
}

In the code above:

  • We start with an integer number that you want to format with leading zeroes.

  • We specify the desired width of the resulting string in the width variable.

  • Using String.format(), we create a format string that includes %0 followed by the width and d for formatting an integer. The %0 specifies that leading zeroes should be added.

  • We then use String.format() with the format string to create the formattedNumber string.

  • Finally, we print the result to the console.

When you run this code, you will see that the formattedNumber variable contains the original number with leading zeroes added to achieve the specified width. You can adjust the width variable to control the number of leading zeroes you want to add.


More Tags

apple-push-notifications nullable exacttarget pwd flying-saucer angular8 osx-elcapitan keyboard-events nserror azure-blob-storage

More Java Questions

More Biology Calculators

More Fitness Calculators

More Chemistry Calculators

More Physical chemistry Calculators