5
$\begingroup$

I want to export data nicely with NumberForm, However it displays Ok in the note book, but not the exported file.

Here is the code:

lst = {{1/10, 1/3}, {1/3, Pi}};
lst = N[lst, 10]
SetDirectory[NotebookDirectory[]];
Export["testlst.txt", lst, "Table"];

The output in the notebook is:

{{0.1000000000, 0.3333333333}, {0.3333333333, 3.141592654}}

However in the txt file it looks like(ugly, not easy to read):

0.1 0.3333333333
0.3333333333    3.141592654

How to fix this? or How to achieve the format specification such as %15.4lf like in c?

$\endgroup$
5
  • 1
    $\begingroup$ lst = NumberForm[lst // N, {11, 10}] $\endgroup$
    – Bob Hanlon
    Dec 27, 2015 at 2:05
  • 1
    $\begingroup$ @BobHanlon but you can't export it in the table form $\endgroup$ Dec 27, 2015 at 3:46
  • $\begingroup$ Your statement that "The output in the notebook is: {{0.1000000000, ..." is simply wrong. What we get in the Notebook is: screenshot. Please correct your question formulation. $\endgroup$ Dec 27, 2015 at 17:18
  • $\begingroup$ @AlexeyPopkov I miss a 10 in the code after the comma $\endgroup$ Dec 28, 2015 at 0:22
  • $\begingroup$ The ToString command appears to preserve format. $\endgroup$
    – user1722
    Aug 28, 2018 at 18:55

1 Answer 1

8
$\begingroup$

I mapped NumberForm, padding to the left with spaces and to the right with zeroes, at the lowest level of your table

numbers = 
  Map[
    NumberForm[#, {11, 10}, NumberPadding -> {" ", "0"}] &, 
    N[{{1/10, 1/3}, {1/3, Pi}}, 10], 
    {-1}]

and then exported it to my desktop

Export[FileNameJoin[{$HomeDirectory, "Desktop", "test.txt"}], numbers, "Table"]

The output file looked like this:

file

which I think is pretty much what you want.

$\endgroup$
1
  • $\begingroup$ (+1) But this solution works only starting from Mathematica version 9. $\endgroup$ Dec 27, 2015 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.