# Thread: printf , decimal places

1. ## printf , decimal places

Hi ,

I have a beginners question , I would like to print variable with 2 decimal places.

printf("%.2f",a); all nice and dandy , but what if i want to set decimal places dynamically.

Example (i know this doesnt work, just for demonstration what I need ):

int dec=2;
printf("%.%decf",dec,a);

Is it posible to do it this way ?

2. Code:
`printf("%.*f\n",dec,a);`

3. Originally Posted by Bayint Naung
Code:
`printf("%.*f\n",dec,a);`
Can you kindly explain it's working to me please....
Thanks.

4. Use *

Originally Posted by a printf manual
The precision

An optional precision, in the form of a period ('.') followed by an optional decimal digit string. Instead of a decimal digit string one may write '*' or '*m\$' (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. If the precision is given as just '.', or the precision is negative, the precision is taken to be zero. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions.

5. Originally Posted by tortelini
Hi ,

I have a beginners question , I would like to print variable with 2 decimal places.

printf("%.2f",a); all nice and dandy , but what if i want to set decimal places dynamically.

Example (i know this doesnt work, just for demonstration what I need ):

int dec=2;
printf("%.%decf",dec,a);

Is it posible to do it this way ?
You do realize that you can compose the formatting string dynamically...
Code:
```char s[50] = {0};

strcpy(s,"%d %.2f");
printf(s,x,y);```