Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

printf

I want to control the number of exponent digits after 'e' in C printf %e?

For example, C printf("%e") result 2.35e+03, but I want 2.35e+003, I need 3 digits of exponent, how do I 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, I got the right results in Windows with MinGW.

like image 240
user1024 Avatar asked Jul 10 '15 02:07

user1024


People also ask

What is E in printf?

e directs that the number is printed: (sign), 1 digit, '. ' , followed by some digits and an exponent. The 2nd 2 in "%2.2e" is the number of digits after the decimal point to print. 6 is used if this 2nd value is not provided.

What is %E format specifier?

a floating point number in scientific notation. %E. a floating point number in scientific notation. %% the % symbol.


1 Answers

"...The exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent. ..." C11dr §7.21.6.1 8

So 3.45e+07 is compliant (what OP does not want) and 3.45e+007 is not compliant (what OP wants).

As C does not provide a standard way for code to alter the number of exponent digits, code is left to fend for itself.

Various compilers support some control.

visual studio _set_output_format

For fun, following is 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 than 3
  }
  puts(buf);

  3.452e00007

Also see c++ how to get "one digit exponent" with printf

like image 151
chux - Reinstate Monica Avatar answered Oct 21 '22 09:10

chux - Reinstate Monica