The standard solution here would be printf("%.*d", precision, number);
in the printf family, in C, the precision formatting field specifies a
minimum number of digits to be displayed, defaulting to 1. This is
independent of the width, so you can write things like:
printf("%6.3d", 12); // outputs " 012"
printf("%6.0d", 0); // outputs " ", without any 0
For either the width or the precision (or both), you can specify '*',
which will cause printf to pick the value up from an argument (pass an
int):
printf("%6.*d", 3, 12); // outputs " 012"
printf("%*.3d", 6, 12); // outputs " 012"
printf("%*.*d", 6, 3, 12); // outputs " 012"
Regretfully, there is no equivalent functionality in ostream: the
precision is ignored when outputting an integer. (This is probably
because there is no type dependent default for the precision. The
default is 6, and it applies to all types which respect it.)