Is there any difference in using %f, %e, %g, %E or %G with scanf?

%f prints the number as a decimal floating point number, e.g. 214.52. %e prints the number in scientific notation, e.g. 214.52e+2. %g prints the number in the shortest among two, e.g. In the above two examples, if I want to print the number through %g then it would be 214.52 but not the 2.145e+2 as it is longer.

#include<stdio.h>
int main(int argc, char *argv[]) {
    float f=214.52;   
    printf("%f\n",f); // 214.520004
    printf("%e\n",f); // 2.145200e+02
    printf("%g\n",f); // 214.52
}

f,e,g all are for Floating point number

From the doc:-

A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by strtod). Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X.

Also check this reference which says that it(f,e,g) matches a floating-point number.


The above answer refers to C++, but the same is true for C.

From "7.19.6.2 The fscanf function" in the "Final version of the C99 standard with corrigenda TC1, TC2, and TC3 included, formatted as a draft" (link copied from http://en.wikipedia.org/wiki/C99):

a,e,f,g
Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.

The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.

So %f, %e, %g, %E, %G all behave identically when scanning numbers, as you experienced.


C displays both float and double variables to six decimal places. This does NOT refer to the precision (accuracy) of which the number is actually stored, only how many decimal places printf() uses to display these variable types.

The following program illustrates how the different data types are declared and displayed:

#include <stdio.h>

main()
{

    float   a = 23.567;
    double  b = 11e+23;

    printf("Float variable is %f\n", a);
    printf("Double variable is %e\n", b);
}

OUTPUT

Float variable is 23.567000
Double variable is 11.000000e23