# How should I export data with desired precision to output file

I want to control the number of decimal points in the output file.

input={33.04177277115046 + 8.9984286747054116/e^4,
1.56875          + 1.52284*10^-7/e^4 }


I want to export it in a file with say 4 decimal points to be printed.

(not working: Exporting data to txt file)

Expected output

{33.0418 + 8.9984/e^4,
1.5688 + 1.5228*10^-7/e^4 }

• So, if a number is less than .0001 it should be printed in scientific notation with 5 digits of precision, but if it is more than .0001 it should be printed in decimal notation with 4 digits of accuracy? Seems odd. Commented Mar 10, 2021 at 0:07
• @CarlWoll, the input that I have provided here is an actual Mathematica output. My purpose is to round off all the numbers to say 4th decimal. So at the first step, I won’t mind the discrimination i.e. the second entry could be just 1.5688 + 0.0000/e^4 inside the output file which I failed to produce so far. The problem is I need to keep track it is 0.0000/e^4 Not just 0.0000 Commented Mar 10, 2021 at 0:14
• input /. Plus[x_, Times[y_, z_Power]] :> ToString@NumberForm[x, {\[Infinity], 4}] <> " + " <> ToString@NumberForm[Round[y, 0.0001], {\[Infinity], 4}] <> "/" <> ToString[z[[1]]] <> "^" <> ToString[-z[[2]]] Commented Mar 10, 2021 at 8:00

Here is a workaround:

We first create a string in order to prevent MMA to automatically format it. Then we pick out the numbers, format them to the specified number of digits and finally change them back to strings and insert them:

input = {33.04177277115046 + 8.9984286747054116/e^4,
1.56875 + 1.52284*10^-7/e^4}
setDigits[input_, nDigits_] :=
StringReplace[ToString[input // InputForm],
x : RegularExpression["(\\d+\\.?\\d*)"] :> ToString[NumberForm[ToExpression[x], {\[Infinity],nDigits}]]  ]


With this we can now transform our output into a string, that can be exported without further unwanted formatting:

setDigits[input, 4]

(* "{33.0418 + 8.9984/e^4, 1.5688 + 1.5228*^-7/e^4}" *)