# Thread: round up to x decimals in printf

1. ## round up to x decimals in printf

Hello again ^^

Code:
double rou=3.14195;
printf("%f rounded = %.4f\n\n", rou, rou);
output: 3.14195 rounded = 3.1420

Is it posible for me to put a variable where the number 4 is?
So I can round up to x decimals instead of a constant?

Thanks for your time and help

2. First create a format string using sprintf(). Then supply that format string to the printf() call.

3. try to put something like that in a function
Code:
int num_dec = 4;
double rou=3.14195;
char fmt[32];
sprintf(fmt,"%f rounded = %%0.%df\n\n", rou,num_dec);
printf(fmt, rou);
Kurt

4. You can put an * in the format specifier:
Code:
printf("%f rounded to %d places is %.*f\n", rou, num_dec, num_dec, rou);
That * in blue means that you are going to pass the precision for the %f as the next parameter to printf.

5. Thank you for your quick replies!
Really appreciate it!
Used andurils462 method at the end.
Solved my problem.

Thanks again for your time and help!

Lolo