How to write string (float) to file?

Rainer Deyke root at rainerdeyke.com
Tue Aug 28 23:32:13 CEST 2001


"Tim Peters" <tim.one at home.com> wrote in message
news:mailman.999028783.18165.python-list at python.org...
> [Tim]
> > ...
> > 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.
>
> [Rainer Deyke]
> > c = (((a * 200) / b) + 1) / 2
> > s = '%03d' % c
> > file.write(s[:-2] + '.' + s[-2:])
>
> So that, e.g., 1/200 rounds to '0.01', but (-1)/200 rounds to '0.00' and
> loses the minus sign?  '%.2f' looks better all the time <0.2f wink>.

If you're that picky about accuracy, floats are definitely the wrong choice.

>>> '%.2f' % (0.005)
'0.01'
>>> '%.2f' % (0.015)
'0.01'
>>> '%.2f' % (0.025)
'0.03'

If you want symmetry about 0, that's easy enough:

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

But why stop there?  Why not use accountant rounding (i.e. when rounding to
the nearest multiple of N, if a number is exactly between two multiples of
N, pick the one which is a multiple of 2 * N)?

c / (a * 100) / b
n = (a * 100) % b
if n * 2 > b: c += 1
elif n * 2 == b:
  c += (c & 1)
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