Skip to content
Related Articles

Related Articles

Improve Article

Using a variable as format specifier in C

  • Difficulty Level : Medium
  • 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.




// C program to demonstrate use of variable
// in format specifier.
#include <stdio.h>
  
int main()
{
    float b = 6.412355;
  
    // using the format specifier %.*f
    // a = 3 will print value of b upto
    // 3 decimal places
    int a = 3;
    printf("%.*f\n", a, b);
  
    // a = 5 will print value of b upto
    // 3 decimal places
    a = 5;
    printf("%.*f\n", a, b);
    return 0;
}

Output:

6.412
6.41235

This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :