# How does one specify numerical precision for FortranForm[] and CForm[]

I have a long function composed of polynomials and exponentials that I would like to convert to an appropriate form to cut and paste as an equation into SolidWorks. FortranForm gets me close and with a few substitutions I have the correct syntax. However the output displays 16 digits of precision. This is fine for a short function but for longer polynomial functions it causes the text to be too long for the equation input window. I would like to reduce the precision of the output to 4 or 5 significant digits.

Here is a simplified example:

ToString[FortranForm[1/0.123456789 x^2 + E^(-z^2/0.123456789)]];
StringReplace[%, {"E**" -> "exp", "**" -> "^"}]

(* "exp(-8.100000073710001*z^2) + 8.100000073710001*x^2" *)


I haven't been able to get NumberForm or Round to work, for example the input below still has 16 digits of precision in the fortran output.

NumberForm[1/3. x^2, 4]
FortranForm[%]


and Round doesn't seem to work with expressions.

Round[1/3. x^2, 0.001]

(* Round[0.333333 x^2, 0.001] *)

• Would it make a difference if you set a narrower page width, so FortranForm generates appropriate line breaks? Something like: InternalInheritedBlock[{$Output}, SetOptions[$Output, PageWidth -> 32]; FortranForm[N[Pi, 100]] ]. – MarcoB Jun 11 '18 at 17:49
• I did have to set the PageWidth to eliminate the line breaks but that did not seem to affect the precision. – Rudy Potter Jun 11 '18 at 18:14

I think CForm and FortranForm both produce the same format for decimal and scientific numbers, so you could do:

fortranString[expr_]:=InternalInheritedBlock[{Real},
Unprotect @ Real;
Format[r_Real,FortranForm] := Format[SetPrecision[r,5], CForm];
ToString[expr, FortranForm]
]


fortranString[1/0.123456789^50 x^2 + E^(-z^2/0.123456789)]