Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Float Format Specifier in C

Is there any way to have a user inputed float format specifier? For example, if I print this.

float c = 15.0123
printf("%.2f", c);

// outputs: 15.01

How can I assign the number of decimal places to a variable? Like:

int n = 3;
float c = 15.0123
printf("%.(%i)f", n, c);

// outputs: 15.012
like image 973
atb Avatar asked Mar 09 '12 00:03

atb


People also ask

What is format specifier of float?

%f. a floating point number for floats. %u. int unsigned decimal. %e.

What is the format for float in C?

Float is a datatype which is used to represent the floating point numbers. It is a 32-bit IEEE 754 single precision floating point number ( 1-bit for the sign, 8-bit for exponent, 23*-bit for the value. It has 6 decimal digits of precision.

What is format specifier in C?

The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.

How do printf ()' s format specifiers %E and %f differ in their treatment of floating point numbers?

%e %e represents the data in exponential power(scientific format), 'e' would be by default mean exponential power 10. %f %f represents the data in normal decimal form, upto six decimal places, although you can control, that upto how many decimal places did you want your output.


2 Answers

The precision can be specified by an argument with the asterisk *. This is called an argument-supplied precision.

float c = 15.0123;
int m = 2;
printf("%.*f", m,  c);
like image 171
ouah Avatar answered Oct 12 '22 10:10

ouah


printf("%.*f", n, c); that will print out c with n places after the decimal.

like image 24
twain249 Avatar answered Oct 12 '22 12:10

twain249