Since Java 1.5 you can use the String.format
method. For example, to do the same thing as your example:
String format = String.format("%%0%dd", digits);
String result = String.format(format, num);
return result;
In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:
%% --> %
0 --> 0
%d --> <value of digits>
d --> d
So if digits is equal to 5, the format string becomes %05d
which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format
for more information on the conversion specifiers.