3
printf("%.2f",..);

I want to control the number 2 in the example above, put a variable instead of the the number 2.

so if

int var=5;

the argument of printf will be "%.5f".

Is it possible? Thanks.

Signer3
  • 101
  • 1
  • 1
  • 8

2 Answers2

5

This should work for you:

A little example program to test it:

#include <stdio.h>

int main() {

    float f = 4.3234;
    int x = 2;

    printf("%.*f", x, f);

    return 0;

}

For more information see: http://www.cplusplus.com/reference/cstdio/printf/

Rizier123
  • 58,877
  • 16
  • 101
  • 156
-1

Check this

int main(int argc, char* argv[])
{
    char format[16];
    int  number;

    number = 5;

    snprintf(format, sizeof(format), "%%.%df", number);
    printf("%s\n", format);
    return 0;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97