<p>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)</p>

<pre><code>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 &lt; zeroes; i++) {
        s.append(0);
    }
    return s.append(num).toString();
}
</code></pre>

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