Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The sub-specifier in printf

Tags:

c

printf

mingw32

int main ()
{
    float Num = 3254.4;
    printf("%06.4f",Num);
    return 0;
}

Why it doesn't print 003254.3999 as my expectation, but 3254.3999?

I've completely read this reference before posting.

like image 528
Kevin Dong Avatar asked Dec 18 '13 17:12

Kevin Dong


4 Answers

From your Reference:

width:

Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

Note that this counts all characters including the . and the four decimal places

6 to the left + 4 to the right + 1 for decimal = 11 (not 10)

What you want is "%011.4f"

Tested this:

printf("%011.4f\n", 1.4);

result is:

000001.4000  // note 6 to the left and 4 to the right (plus the .) = 11
like image 104
Glenn Teitelbaum Avatar answered Oct 08 '22 05:10

Glenn Teitelbaum


Change the 6 to 10 or greater and you will see the 0 padding. The 6 you are specifying is the minimum characters it'll print. Your number (3254.3999) has nine.

like image 26
Fiddling Bits Avatar answered Oct 08 '22 05:10

Fiddling Bits


Try this:

int main ()
{
    float Num = 3254.4;
    printf("%011.4f",Num);
    return 0;
}

ie, try to change the specifier value greater than 6 since you are specifying the minimum characters limit.

like image 29
Rahul Tripathi Avatar answered Oct 08 '22 04:10

Rahul Tripathi


This is because 6 is used to right justify the output to 6 places. Since the output comes to be width of 9 places its effect is not visible.If you increase the width then you can see the effect.

like image 32
haccks Avatar answered Oct 08 '22 04:10

haccks