I would like to make the output of a number to always have 6 digits
e.g.:
How can I do this with printf
/sprintf
?
printf and its variants can pad zeroes to the left, not to the right. sprintf the number, then add the necessary zeros yourself, or make sure the number is 6 digits long:
while(num < 100000)
num *= 10;
(This code assumes the number isn't negative, or you're going to get in trouble)
printf
will return the number of character printed out. This you can print out the remaining zeros:
int num = 3; // init
int len = printf("%d", num);
for (int i = 0; i < 6-len; ++i)
printf("0");
You should add some error checks (for example, if len
is larger than 6).
With sprintf
, you can use memset
on the remaining buffer, which will be easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With