Using a variable as format specifier in C
Last Updated :
29 May, 2017
It is known that, printf() function is an inbuilt library function in C programming language in the header file stdio.h. It is used to print a character, string, float, integer etc. onto the output screen. However, while printing the float values, the number of digits following the decimal point can be controlled by the user. One of the ways to do that is by using formats like %.2f etc. But variables can also be used for formatting format specifiers.
Below example shows how this can be done.
#include <stdio.h>
int main()
{
float b = 6.412355;
int a = 3;
printf ( "%.*f\n" , a, b);
a = 5;
printf ( "%.*f\n" , a, b);
return 0;
}
|
Output:
6.412
6.41235
Share your thoughts in the comments
Please Login to comment...