Hel Hel - 7 days ago 7
C Question

How to align mutiple decimal percentage with printf

For percentage in form "x.%x", the first x <= 3 bits, the second x == 2 bits

a1 = 93.11;
a2 = 33.72;
a3 = 30.69;
b1 = 0.00;
b2 = 0.00;
b3 = 0.00;
printf("%3.2f%% %3.2f%% %3.2f%%\n", a1, a2, a3); // wrong, how to modify?
printf("%3.2f%% %3.2f%% %3.2f%%\n", b1, b2, b3);


Output:

93.11% 33.72% 30.69%

0.00% 0.00% 0.00%

But the output is not right. How to align to make output below:

enter image description here

Answer

I believe you want:

printf("%5.2f%% %5.2f%% %5.2f%%\n", a1, a2, a3);
printf("%5.2f%% %5.2f%% %5.2f%%\n", b1, b2, b3);

The 5 means, print at least 5 characters.

12345
93.11  <== 5 total characters, counting the decimal point.
 0.00  <== 5 total characters, first char is a [space]

Link to IDEOne Code

The output is:

93.11% 33.72% 30.69%
 0.00%  0.00%  0.00%