Home > Java > javaTutorial > How to Add Leading Zeroes to Numbers in Java?

How to Add Leading Zeroes to Numbers in Java?

Barbara Streisand
Release: 2024-12-21 10:23:10
Original
138 people have browsed it

How to Add Leading Zeroes to Numbers in Java?

Add Leading Zeroes to Number in Java

This article provides a solution to adding leading zeroes to a number in Java.

Custom Method

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();
}
Copy after login

String.format() Method (Java 5 )

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);
Copy after login

In this example:

  • d specifies that the number should be formatted as a decimal integer with a minimum width of 3 characters.
  • Leading zeroes will be used to pad the number to the specified width.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template