The standard solution here would be printf("%.*d", precision, number)
; in the printf
family in C, the precision formatting field indicates the minimum number of digits to display, the default is 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 width or precision (or both), you can specify '*'
, which will cause printf
select a value from the argument (pass int
):
printf("%6.*d", 3, 12); // outputs " 012" printf("%*.3d", 6, 12); // outputs " 012" printf("%*.*d", 6, 3, 12); // outputs " 012"
Unfortunately, there is no equivalent functionality in ostream
: accuracy is output when outputting an integer. (This is probably because it is type-independent for accuracy. The default is 6, and applies to all types that respect it.)
source share