4

I am saving some data with numpy.savetxt(path,array,fmt="%.2f %.2f %.2f %.2f %.2f") and I want the text file to be formated nicely. I would like to limit the floats to a certain amount of digits, like this:

11.2345 -> 11.2
1.2345 -> 1.23

Currently I get:

11.2345 -> 11.23
1.2345 -> 1.23

This destroys the layout of the text file.

I know that there are a couple of similar questions on SO, however I was not able to apply any of the solutions to numpy.savetxt().

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sasha
  • 1,338
  • 2
  • 13
  • 22

1 Answers1

4

Try using fmt="%9.2f". It seems to give nice results for me:

    25.72    433.54    135.69    898.93
   177.46    120.65    954.13    480.82
   963.45    774.35    289.08     93.64
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • I have already tried this and thought it does not work. However I have just noticed that this is because there were some long integers in front that caused the shifting. I would still like to know if one can fix the total number of digits. For example, in your caseČ instead of 25.72 to get 25.720 . – Sasha Apr 14 '13 at 11:24
  • 1
    Yeah, you just have to choose a big enough number before the point. I hope that's not a problem in itself? If you want 25.720, just use "%9.3f". – John Zwinck Apr 14 '13 at 11:26
  • And what would happen if I were printing 1234.567? would it get reduced to 1234.5? Just to clarify: Your solution corrects the formating problem. However since a single line contains in total over 40 floats and 5 integers, The more spaces I add to make the formating safe, the harder the file is to read at 1920x1080. Currently,with %5.2f, I have to scroll to see the whole line. %4.2f makes some numbers join. – Sasha Apr 14 '13 at 11:33
  • 2
    No. Now what you're asking for can't be done without custom code, I'm afraid. Just pick a sufficiently large LHS, or maybe reconsider whether you really need these magic-width text files...e.g. you can just write CSV and open in Excel or Calc or whatever. – John Zwinck Apr 14 '13 at 11:36
  • That is a good idea. Thank You for Your help. I thought that the solution and its implementation in python is trivial. – Sasha Apr 14 '13 at 11:39