Question

I want to print out a float with a user-defined precision after decimal point in C, like say,

int dec;
float no;
printf("\nEnter no of decimal places and the number ");
scanf("%d%f",&dec,&no);

Then print the number no with dec decimal places.

Was it helpful?

Solution 2

Do

int dec;
float no;
printf("\nEnter no of decimal places and the number ");
scanf("%d%f",&dec,&no);
printf("%.*f",dec,no);

OTHER TIPS

You may format the printing of a floating point number, but not its actual size.

You may read this on formatting floating point number.

To save your time, you may use the %f format specifier, as

printf("%.PRECISIONf", fvar);

where PRECISION is the number of digits you want after decimal, for e.g.

int 
print_float(float fvar, unsigned int precision) {
  char fs[32];
  sprintf(fs,"%%.%df", precision);
  return printf(fs, fvar);
}

On calling the routine:

print_float(2.0f, 2);

you will get 2.00 as the output.

Hope this solves your issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top