Add Leading Zeroes to Number in Java
This article provides a solution to adding leading zeroes to a number in Java.
A custom method called intToString is created to address this requirement. It takes the original number (num) and the desired number of digits. It calculates the number of zeroes needed to equal the desired number of digits based on the number of digits in num. Then, it appends the zeroes and the original number to a StringBuffer before converting it to a string.
static String intToString(int num, int digits) { StringBuffer s = new StringBuffer(digits); int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1; for (int i = 0; i < zeroes; i++) { s.append(0); } return s.append(num).toString(); }
Java 5 introduced the String.format() method, which offers a more elegant solution for this task. It allows you to specify the padding and width requirements directly in the format string.
String formatted = String.format("%03d", num);
In this example:
The above is the detailed content of How to Add Leading Zeroes to Numbers in Java?. For more information, please follow other related articles on the PHP Chinese website!