Printf, doubles and decimal places

This example program demonstrates how to print double-precision numbers to a certain number of decimal places using printf.

#include <stdio.h>

int main ()
{
    double a = 1234.56789;
    double b = 299792458;
    double c = 6.62607e-34;

    /* Default printing. */

    printf ("Using %%f (fixed point): %f %f %f.\n", a, b, c);
    printf ("Using %%e (force exponent): %e %e %e.\n", a, b, c);
    printf ("Using %%g (best fit): %g %g %g.\n", a, b, c);

    /* With a width. */

    printf ("Using %%15f: %15f %15f %15f.\n", a, b, c);
    printf ("Using %%15e: %15e %15e %15e.\n", a, b, c);
    printf ("Using %%15g: %15g %15g %15g.\n", a, b, c);

    /* With a width and precision. */

    /* This forces three decimal places. */

    printf ("Using %%15.3f: %15.3f %15.3f %15.3f.\n", a, b, c);

    /* This forces three decimal places of mantissa. */

    printf ("Using %%15.3e: %15.3e %15.3e %15.3e.\n", a, b, c);

    /* This forces two decimal places of mantissa. */

    printf ("Using %%15.3g: %15.3g %15.3g %15.3g.\n", a, b, c);

    /* Let's go crazy. */

    printf ("Using %%15.10f: %15.10f %15.10f %15.10f.\n", a, b, c);
    printf ("Using %%15.10e: %15.10e %15.10e %15.10e.\n", a, b, c);

    /* %g doesn't print trailing zeroes. */

    printf ("Using %%15.10g: %15.10g %15.10g %15.10g.\n", a, b, c);

    return 0;
}

(download)

It outputs the following:

Using %f (fixed point): 1234.567890 299792458.000000 0.000000.
Using %e (force exponent): 1.234568e+03 2.997925e+08 6.626070e-34.
Using %g (best fit): 1234.57 2.99792e+08 6.62607e-34.
Using %15f:     1234.567890 299792458.000000        0.000000.
Using %15e:    1.234568e+03    2.997925e+08    6.626070e-34.
Using %15g:         1234.57     2.99792e+08     6.62607e-34.
Using %15.3f:        1234.568   299792458.000           0.000.
Using %15.3e:       1.235e+03       2.998e+08       6.626e-34.
Using %15.3g:        1.23e+03           3e+08        6.63e-34.
Using %15.10f: 1234.5678900000 299792458.0000000000    0.0000000000.
Using %15.10e: 1.2345678900e+03 2.9979245800e+08 6.6260700000e-34.
Using %15.10g:      1234.56789       299792458     6.62607e-34.


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer