cprintf

C scientific notation exponent format


Is it possible to control number of digits shown in exponent printed by scientific notation (e) of printf?

This code

#include <stdio.h>

int main(void) {
    printf("%6.3e", 403.0);
    return 0;
}

produces (depends on compiler/platform):

4.030e+002 (VS2010) or 4.030e+02 (gcc 4.3.4) or even 4.030e+2

The different number of digits in exponents can easily confuse a diff tool when comparing files generated on different platforms.


Solution

  • The C standard actually specifies how many digits are to be in the exponent (WG14 N1570, §7.21.6.1/p8; N1256, §7.19.6.1/p8):

    The exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent.

    VS2010's implementation is nonconforming. They do provide a library function to change the number of digits printed, which you can use inside a #ifdef wrapper.