Floating-point format specifiers control how floating-point values are formatted by printf(). The conversion specifier determines the notation, while the precision controls the number of digits displayed after the decimal point for %f-style output.
#include <stdio.h>
int main()
{
float a = 3.14159f;
double b = 1234.5678;
long double c = 3.141592653589793L;
printf("float : %f\n", a);
printf("double : %.3f\n", b);
printf("long double : %.15Lf\n", c);
printf("Scientific : %e\n", b);
printf("General : %g\n", b);
return 0;
}
Example Output #
float : 3.141590
double : 1234.568
long double : 3.141592653589793
Scientific : 1.234568e+03
General : 1234.568
Explanation #
The %f conversion displays a floating-point value using decimal notation:
printf("%f\n", a);
The precision can be specified using .n:
printf("%.3f\n", b);
Here, 3 specifies three digits after the decimal point.
Floating-Point Format Specifiers #
| Specifier | Expected argument type | Representation |
|---|---|---|
%f |
double |
Decimal notation |
%e |
double |
Scientific notation |
%E |
double |
Scientific notation with uppercase E |
%g |
double |
%f or %e, whichever is more appropriate |
%G |
double |
%f or %E, whichever is more appropriate |
%Lf |
long double |
Decimal notation |
%Le |
long double |
Scientific notation |
%LE |
long double |
Scientific notation with uppercase E |
%Lg |
long double |
General notation |
%LG |
long double |
General notation |
Precision #
For %f, precision specifies the number of digits after the decimal point:
printf("%.2f\n", 3.14159);
Output:
3.14
For %e and %E, precision specifies the number of digits after the decimal point in the mantissa.
For %g and %G, precision specifies the number of significant digits, and trailing zeros are normally removed.
A float argument passed to printf() is automatically promoted to double, so %f is used for both float and double arguments. For long double, the L length modifier is required.