Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C scientific notation exponent format

Tags:

c

printf

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.

like image 267
Peter Avatar asked Jul 30 '14 06:07

Peter


1 Answers

You cannot do that with C printf().

According to C99 standard doc 7.19.6.1 for %e and %f: The exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent. If the value is zero, the exponent is zero

You could however, write your own wrapper function, where you calculate the base and exponent separately, to get the output in desired format.

Something like:

char* printexponent(double x)
{
    //calculate base here
    //calculate exponent here

    //create the floating point string and return it 
}

Or you could manipulate the output of the printf %e to create your own string.

like image 189
askmish Avatar answered Sep 30 '22 02:09

askmish