How to write string (float) to file?

Tim Peters tim.one at home.com
Tue Aug 28 20:57:44 CEST 2001


[Rainer Deyke, on '%.2f'%(float(a)/b)' as a way to get 2 digits after
 the decimal point]
> That's unreliable.  Use this instead:
>
> c = (a * 100) / b
> s = '%03d' % c
> file.write(s[:-2] + '.' + s[-2:])

Rainer, your loathing of fp is fine as a personal choice, but let's not
poison our youth without stronger cause than this <wink>.  My bet is the
poster would rather, e.g., see '0.67' than '0.66' given a=2 and b=3.  If
you're going to fake fp by hand, then you're responsible for faking all of
it, incl. sensible rounding.






More information about the Python-list mailing list