How to control the number of exponent digits after 'e' in C printf %e? -


i want control number of exponent digits after 'e' in c printf %e?

for example, c printf("%e") result 2.35e+03, want 2.35e+003, need 3 digits of exponent, how use printf?

code:

#include<stdio.h> int main() {     double x=34523423.52342353;     printf("%.3g\n%.3e",x,x);     return 0; } 

result: http://codepad.org/dslzqirn

3.45e+07 3.452e+07 

i want

3.45e+007 3.452e+007 

but interestingly, got right results in windows mingw.

"...the exponent contains @ least 2 digits, , many more digits necessary represent exponent. ..." c11dr §7.21.6.1 8

so 3.45e+07 compliant (what op not want) , 3.45e+007 not compliant (what op wants).

as c not provide standard way code alter number of exponent digits, code left fend itself.

various compilers support control.

visual studio _set_output_format

for fun, following diy code

  double x = 34523423.52342353;   //                    - 1 . xxx e - eeee \0   #define expectedsize (1+1+1 +3 +1+1+ 4 + 1)   char buf[expectedsize + 10];   snprintf(buf, sizeof buf, "%.3e", x);   char *e = strchr(buf, 'e');  // lucky 'e' not in "infinity" nor "nan"   if (e) {     e++;     int expo = atoi(e);     snprintf(e, sizeof buf - (e - buf), "%05d", expo);  // 5 more illustrative 3   }   puts(buf);    3.452e00007 

also see c++ how "one digit exponent" printf


Comments