Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top