1

I would like to export in txt or tsv format a table that contains both alphameric and numeric entries, but I would like the numeric entries to be exported in Fortran format.

For example 1.234E-9.

Is there a convenient way to to this, or must I build strings?

creidhne
  • 5,055
  • 4
  • 20
  • 28
David Keith
  • 4,340
  • 1
  • 12
  • 28
  • 1
    There is an actual FortranForm function. Didn't check to see what happens if you export a FortranForm expression directly, but if the FortranForm head comes through, then you would just use ToString to clean that up. Or maybe some Export option. – lericr Jun 22 '23 at 22:48
  • I have found that exporting to a file using TSV format works for this. To avoid quotes on text I used TextDelimiters -> “”. I could not find a way to set the threshold at which numbers were expressed in E notation. I would like to see Wolfram put more effort into formatting material intended to be read by other programs. I did not find the earlier answers useful. – David Keith Jun 28 '23 at 22:51

1 Answers1

1

This was based on one of the answers from here

ClearAll[FortranReal] ;
SetAttributes[FortranReal, Listable] ;
FortranReal[
number_Real,
precision_Integer: Ceiling[$MachinePrecision] + 1 ,
kind_String: ""
] := Block[
  {mantissa, exponent, sign},
  {mantissa,exponent} = If[SameQ[number,N[0,Precision[number]]],List[N[0,Precision[number]],1],MantissaExponent[number]] ;
  mantissa = N[Times[10,mantissa],precision] ;
  mantissa = NumberForm[mantissa,Rule[DefaultPrintPrecision,precision]] ;
  exponent = Subtract[exponent,1] ;
  sign = Sign[exponent] ;
  sign = Which[GreaterEqual[sign,0],"+",Less[sign,0],"-"] ;
  exponent = Abs[exponent] ;
  mantissa = ToString[mantissa] ;
  mantissa =  StringTrim[mantissa,"0"..] ;
  mantissa = If[SameQ[mantissa,"."],"0.",mantissa] ;
  If[UnsameQ[exponent,0],StringTemplate["`1`E`2``3``4`"][mantissa,sign,exponent,kind],StringTemplate["`1``2`"][mantissa, kind]]
] ;

Examples:

FortranReal[100.0*Pi]
FortranReal[{0.1*N[E], N[E], 10*N[E]}]
FortranReal[{0.1*N[E], N[E], 10*N[E]}, 3]
FortranReal[{0.1*N[E], N[E], 10*N[E]},Ceiling[$MachinePrecision] + 1 , "_REAL64" ]
(* "3.141592653589793E+2" *)
(* {"2.7182818284590455E-1","2.7182818284590446","2.7182818284590446E+1"} *)
(* {"2.72E-1","2.72","2.72E+1"} *)
(* {"2.7182818284590455E-1_REAL64","2.7182818284590446_REAL64","2.7182818284590446E+1_REAL64"} *)
I.M.
  • 2,926
  • 1
  • 13
  • 18