TransWikia.com

How should I export data with desired precision to output file

Mathematica Asked on July 5, 2021

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 }

One Answer

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}" *)

Answered by Daniel Huber on July 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP