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$
  • 1
    $\begingroup$ lst = NumberForm[lst // N, {11, 10}] $\endgroup$ – Bob Hanlon Dec 27 '15 at 2:05
  • 1
    $\begingroup$ @BobHanlon but you can't export it in the table form $\endgroup$ – an offer can't refuse Dec 27 '15 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$ – Alexey Popkov Dec 27 '15 at 17:18
  • $\begingroup$ @AlexeyPopkov I miss a 10 in the code after the comma $\endgroup$ – an offer can't refuse Dec 28 '15 at 0:22
  • $\begingroup$ The ToString command appears to preserve format. $\endgroup$ – barrycarter Aug 28 '18 at 18:55
7
$\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$
  • $\begingroup$ (+1) But this solution works only starting from Mathematica version 9. $\endgroup$ – Alexey Popkov Dec 27 '15 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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