How to write string (float) to file?

Rainer Deyke root at rainerdeyke.com
Tue Aug 28 21:30:01 CEST 2001


"Tim Peters" <tim.one at home.com> wrote in message
news:mailman.999025123.7905.python-list at python.org...
> [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.

c = (((a * 200) / b) + 1) / 2
s = '%03d' % c
file.write(s[:-2] + '.' + s[-2:])


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list