# Add leading zeroes to number in Java?

###### Posted By: Anonymous

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

###### Answered By: begray

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.