Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Correct format specifier for double in printf

What is the exact form specifier for a double in print f? Is it %f or is it %lf? I believe it's %f, but I am not sure.
Code sample
#include <stdio.h>

int main()
{
double d = 1.4;
printf("%lf", d); // Is this wrong?
}
by

4 Answers

rahul07
"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).
RoliMishra
Format %lf is a perfectly correct printf format for double, exactly as you used it. There's nothing wrong with your code.

Format %lf in printf was not supported in old (pre-C99) versions of C language, which created superficial "inconsistency" between format specifiers for double in printf and scanf. That superficial inconsistency has been fixed in C99.

You are not required to use %lf with double in printf. You can use %f as well, if you so prefer (%lf and %f are equivalent in printf). But in modern C it makes perfect sense to prefer to use %f with float, %lf with double and %Lf with long double, consistently in both printf and scanf.
sandhya6gczb
for printf the following specifiers and corresponding types are specified:

%f -> double
%Lf -> long double.
and for scanf it is:

%f -> float
%lf -> double
%Lf -> long double
kshitijrana14
It can be %f, %g or %e depending on how you want the number to be formatted.The l modifier is required in scanf with double, but not in printf.

Login / Signup to Answer the Question.