HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Add leading zeroes to number in Java?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
javaleadingaddzeroesnumber

Problem

Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)

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

Solution

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);


  • 0 - to pad with zeros



  • 3 - to set width to 3

Code Snippets

String formatted = String.format("%03d", num);

Context

Stack Overflow Q#275711, score: 1560

Revisions (0)

No revisions yet.