Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trailing Zeros in printf/sprintf

Tags:

c

printf

I would like to make the output of a number to always have 6 digits

e.g.:

  • if number is 1 the output should be 100000
  • if number is 23 the output should be 230000
  • if number is 236 the output should be 236000

How can I do this with printf/sprintf?

like image 301
Manu Avatar asked Feb 22 '23 07:02

Manu


2 Answers

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)

like image 198
zmbq Avatar answered Mar 07 '23 03:03

zmbq


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.

like image 33
fefe Avatar answered Mar 07 '23 03:03

fefe