Printf float with number of trailing zeros in variable

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

      

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

therefore if

int var=5;

      

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

Is it possible? Thank.

+3


source to share


2 answers


This should work for you:

A small sample program for testing:



#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/

+5


source


check it



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;
}

      

-1


source







All Articles