Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a variable number of digits of a double using printf

Tags:

c

printf

Anyone knows if it is possible to use printf to print a VARIABLE number of digits?

The following line of code prints exactly 2:

printf("%.2lf", x);

but let's say I have a variable:

int precision = 2;

Is there a way to use it in printf to specify the number of digits?

Otherwise I will have to write a 'switch' or 'if' structure.

Thanks

like image 937
pHbits Avatar asked Sep 01 '13 10:09

pHbits


2 Answers

It is possible:

#include <stdio.h>

int main() {
    int precision = 3;
    float b = 6.412355;
    printf("%.*lf\n",precision,b);
    return 0;
}
like image 120
AVX Avatar answered Sep 22 '22 12:09

AVX


Yes, you can do that easily -

int precision = 2;
printf("%.*lf", precision, x);
like image 27
MD Sayem Ahmed Avatar answered Sep 22 '22 12:09

MD Sayem Ahmed