Reputation:
Im trying to print out a format of lets say x levels of accuracy meaning it should print if x = 10
float foo;
printf("levels of accuracy %.10f", foo);
What i've tried: I already have the math to convert the x to the desired decimal place. something like..
int multiplier = 10;
float initialaccuracy = 1.0;
float threshold = initialaccuracy / ((float)(pow(multiplier, accuracy)));
What I want to know:
How do i use the format of that x into the printf so if i pick x= 4 it would be %.4f or if i pick 15 it would be %.15f, without hardcoding those values just using it of whatever i pass in?
Upvotes: 1
Views: 51
Reputation: 4444
Or, build your format string 'on the fly'...
char fmt[99];
sprintf(fmt,"levels of accuracy %%.%df",accuracy);
printf(fmt,foo);
Upvotes: 0
Reputation: 225342
You can put a *
in place of the precision specifier and pass it as a separate parameter:
int accuracy = 10;
printf("levels of accuracy %.*f", accuracy, foo);
Upvotes: 3