1

I'm writing floating point numbers to a text file and I'd really appreciate if Python would stop writing numbers like "0.000002" as "2e-6". What can I do?

mskfisher
  • 3,291
  • 4
  • 35
  • 48

2 Answers2

2

You could use formatting directives, such as this one:

n = 0.000002
print('{:f}'.format(n))
0.000002

more information about formatting see these Python docs

Or old-style if working pre Python v2.6 (thanks @mgilson and @artSwri)

print('%f' % n)
Levon
  • 138,105
  • 33
  • 200
  • 191
  • This raises a ValueError on python 2.6 (OS-X) (ValueError: zero length field name in format) – mgilson May 29 '12 at 19:56
  • @ArtSwri -- I'm using python 2.6. (which meets the requirements) – mgilson May 29 '12 at 19:59
  • @mgilson: Does it work for you if you replace `'{:f}'` with `'{0:f}'`? – Edward Loper May 29 '12 at 20:02
  • 1
    @EdwardLoper -- Yes it does. (one of these days I'm going to get around to learning `.format` in place of `%`) -- I suppose maybe this is the beginning of my education ... – mgilson May 29 '12 at 20:05
  • @mgilson I noticed some inconsistencies with v 2.6.5 under Ubuntu compared to 2.7.3 and 3.2.3 under Windows just this morning. 2.6.5 required more specification information, but worked – Levon May 29 '12 at 20:05
  • @Levon -- I assumed there would be a way to coax it to work -- I just figured that I'd ask in order to document the differences between python versions in the comments here (at very least) – mgilson May 29 '12 at 20:06
  • @mgilson I'm with you (just started yesterday to dig up info on .format .. long time C user I'm very comfy with the whole % thingy) – Levon May 29 '12 at 20:07
1
>>> "%f" % 2e-6
'0.000002'
kenm
  • 23,127
  • 2
  • 43
  • 62