FORTRAN number formatting with c

I want to produce number output exactly as it would be obtained from a FORTRAN program in scientific notation. If I have a number like 31.4159 the FORTRAN output I get from the FORTRAN program is 0.314159E+02 i.e. the "mantissa" is between 0.0 and 1.0. If I do printf using %E in C
printf("%10.6E", 31.14159);
I get
3.141590E+01
i.e. the "mantissa" is between 1.0 and 10.0.

Is there a quick way to get the same format as the FORTRAN output. Thanks in advance.


I don't know of any standard way to do this. However, you can sort of cheat and write your own version...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>

char* format_fortran_float(
  char*    result,  // where to write the formatted number. Must have
  unsigned width,   // room for width + 1 characters.
  double   number
  ) {
  // First, we'll learn the exponent and adjust the number to the range [1.0,0.0]
  int exponent = 0;
  for (; number > 1.0; exponent++) value /= 10;
  for (; number < 0.0; exponent--) value *= 10;

  // Next, we'll print the number as mantissa in [1,0] and exponent
  sprintf( result, "%*fE%+03d", (width - 4), number, exponent );

  // Finally, we'll return the new string
  return result;
  }

int main()
  {
  char buf[ 13 ];
  printf(
    "The number is %s\n",
    format_fortran_float( buf, 12, 31.415926535 )
    );
  return 0;
  }

BTW, I'm at a computer that I can't test the above code on. JSYK.

Hope this helps.
Topic archived. No new replies allowed.