This example shows you how to use the String.format()
method to add zero padding to a number. If you just want to print out the result you can use System.out.format()
. This method is available since Java 1.5, so If you use a previous version you can use the NumberFormat
class, see: How do I format a number with leading zeros?.
package org.kodejava.lang;
public class LeadingZerosExample {
public static void main(String[] args) {
int number = 1500;
// String format below will add leading zeros (the %0 syntax)
// to the number above. The length of the formatted string will
// be 7 characters.
String formatted = String.format("%07d", number);
System.out.println("Number with leading zeros: " + formatted);
}
}
Here is the result of the code snippet above:
Number with leading zeros: 0001500
For more information about the format syntax you can find it here.
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Thank you so much. Looking for this answer. Saved my much time, Jazak Allahu Khairan.