Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precision modifier as a variable in C

Tags:

c

In my program the user inputs the number of decimal places he requires in an output. I save this input as deci. How do I use this variable deci as a precision modifier?

Sample: Input a number: 23.6788766 Input number of decimals: 2 Output: 23.67

like image 972
Chandough Avatar asked Dec 02 '22 18:12

Chandough


2 Answers

If it is C you can do:

float floatnumbervalue = 42.3456;
int numberofdecimals = 2;
printf("%.*f", numberofdecimals, floatnumbervalue);
like image 119
Andres Avatar answered Dec 04 '22 06:12

Andres


In C, for example to change the default precision of 6 digits to 8:

int precision = 8;

printf("%.*f\n", precision, 1.23456789);

The precision argument has to be of type int.

like image 27
ouah Avatar answered Dec 04 '22 07:12

ouah