Arithmetic and Data Types - Display of floating point numbers

Chapter chap4 section 4

All the floating point values we have seen so far have been written using the conventional integral part/decimal point/fractional part notation. The C programming language also supports the well-known "e" notation which is handy for very large or very small floating point numbers.

A floating point number can be written in the form

	"number" e "exponent"

without any internal spaces meaning simply number X 10exponent E may be used instead of e if preferred. Constants written using the "e" notation are normally of type double, they may be forced to other floating point types by appending a suitable letter as described earlier. The output e conversion displays a floating point number in the form shown above. The precision specification specifies the number of digits to appear after the decimal point in the output. Here are some examples in a program
main()
{
        double  x = 1.23456789e+15;
        double  y = 100;
        double  z = 0.5e-15;
        /* shows e format - width=10, precision=5 */
        printf(" x = %10.5le\n y = %10.5le\n z = %10.5le\n",x,y,z);
        /* shows e format - width=20, precision=10 */
        printf(" x = %20.10le\n y = %20.10le\n z = %20.10le\n",x,y,z);
        /* f format with default options */
        printf(" x = %lf\n y = %lf\n z = %lf\n",x,y,z);
}
producing the output
 x = 1.23457e+15
 y = 1.00000e+02
 z = 5.00000e-16
 x =     1.2345678900e+15
 y =     1.0000000000e+02
 z =     5.0000000000e-16
 x = 1234567890000000.000000
 y = 100.000000
 z = 0.000000

printf() also supports the g and G conversions for floating point numbers. These provide "f" conversion style output if the results fit in the field and "e" or "E" style output otherwise. With "g" conversions the precision specification in the field specifies the total number of significant digits to display rather than the number after the decimal point. The following program illustrates the use of the "g" conversion.

main()
{
        double  x = 12.3456789;
        printf("%10.4lg\n",x);
        printf("%10.4lg\n",x*x);
        printf("%10.4lg\n",x*x*x);
        printf("%10.4lg\n",x*x*x*x);
}
producing the output
     12.35
     152.4
      1882
 2.323e+04

For input via scanf() any of the floating point conversion styles can be specified in a scanf() input specification string and any style of floating point number will be accepted and converted.