Search code examples
exportwolfram-mathematicafixed-widthsignificant-digits

How to export a Mathematica list as a fixed-width text file while preserving sig figs?


My first question is how would I export my data in a fixed-width format using Mathematica? My second question is how do I preserve the right most 0's.

For instance, I like to save {{1.12300, 11.12, 111.123},{2.1, 22.123, 222}} into a text file as

1.12300  11.12   111.123
2.10     22.123  222.00

In details, if a number has a mantissa with less than 2 digits, it is matched to 2 via zero padding while if it has more than 2 digits in its mantissa, it would preserve it as it is. It is important for me to distinguish 1.12300 from 1.123. If I use PaddingForm, Mathematica would literally save it as PaddedForm[1.123, {4, 5}] in a text file.


Solution

  • Use

    data = {{1.12300``6, 11.12``3,  111.123``4}, 
            {2.1``2,     22.123``4, 222``2}};
    
    tbl1 = ToString[TableForm[data]];
    tbl2 = StringReplace[tbl, "\n\n" -> "\n"]
    

    to get

    1.12300   11.12    111.123
    2.1       22.123   222.0
    

    If you don't want to enter your data as a set of strings, you need to specify the accuracy of your data using ``. See Numerical Precision tutorial by Mathematica.