Reputation: 801
int main()
{
system("color FC");
const float i=23.1234234;
printf("%5.4f",i);
getch();
return 0;
}
In above code , while printing float data type %5.4
format specifier is used.
I understood that .4
is used to get four numbers after decimal but whats the use of 5
before .4
Upvotes: 0
Views: 5137
Reputation: 106122
5
is used to right justify the output by 5
places. Since the output is 10
character long so the effect is not seen. Now try this
#include <stdio.h>
int main()
{
const float i=23.1234234;
printf("%f\n",i);
printf("%5.4f\n",i);
printf("%7.4f\n",i);
printf("%10.4f\n",i);
printf("%12.5f",i);
return 0;
}
Output:
23.1234234
23.1234
23.1234
23.1234
23.1234
Upvotes: 0
Reputation: 122
5 is used to right justify the output by 5 places i.e. the last digit will occur 5 places from cursor's initial position, if possible.
It is effective only when the length ( including the decimal ) is smaller than what is mentioned in the specifier.
e.g. printf("%5.4f",i);
till the specifier at the place of 5 is smaller than or equal than the length of the output
i.e 2(before decimal) + 4(after decimal, as chosen ) + 1 (the decimal itself) =7 , it has
no effect.
It will have effect here if it is at least 8.
At 7 it does what it should but you won's see any spaces.
Upvotes: 1
Reputation: 83411
The 5
is the length specifier. In this case, the printed float will take up at least 5 spaces. If it is shorter than that, leading spaces will be used.
(Though because of the precision 4
, it will always be at least 6 characters long; the length modifier 5
in this case is a no-op.)
See documentation.
Upvotes: 2