How to write string (float) to file?

Tim Peters tim.one at home.com
Tue Aug 28 23:29:39 EDT 2001


[Rainer Deyke]
> If you're that picky about accuracy, floats are definitely the wrong
> choice.

[Steve Holden]
> Wrong. Tim isn't being picky about accuracy, he's being picky about
> correctly rounding numbers to the required number of decimal places.

Well, nobody can be pickier about accuracy than me, when I'm in the mood for
it <wink>, but that isn't what's going on here.  The original poster was
clearly a newbie, and floating-point formatting was clearly sufficient for
what he was after, not to mention the least work.  Worrying about fp
extremes wasn't appropriate in context, and giving the poor fellow a
sequence of half-baked integer alternatives that are surprising even in
non-extreme cases is right out.

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

The rounding here is trickier than it looks, since none of the inputs
(0.005, 0.015, 0.025) is exactly representable as a binary fp number.
"Trickier" != "unusable", though.

unless-perhaps-you're-rainer<wink>-ly y'rs  - tim





More information about the Python-list mailing list