How to write string (float) to file?

Grant Edwards grante at visi.com
Wed Aug 29 13:06:44 EDT 2001


In article <G89j7.54140$c8.24141594 at news1.denver1.co.home.com>, Rainer Deyke wrote:
>"Grant Edwards" <grante at visi.com> wrote in message
>news:slrn9oq5eu.leu.grante at grante.comtrol.com...
>> In article <bo8j7.54122$c8.24122471 at news1.denver1.co.home.com>, Rainer
>Deyke wrote:
>> > "Grant Edwards" <grante at visi.com> wrote in message
>> > news:slrn9ops86.ks3.grante at grante.comtrol.com...
>> >> After reading a handful of follow-ups, I'm still curious what
>> >> you mean when you say that's unreliable.
>> >
>> >>>> def foo(a, b): return '%.2f' % (float(a)/b)
>> > ...
>
>>
>> Thanks, but that wasn't helpful.  Am I to assume that you're
>> not happy with one of the results?  Which one?  Why do you
>> think it's wrong?
>
>> >>>> foo(1, 200)
>> > '0.01'
>
>Standard rounding: 0.01
>Accountant rounding: 0.00
>
>In this case the result resembles what you get with standard rounding, but
>this is not always the case.  See below.
>
>> >>>> foo(3, 200)
>> > '0.01'

>Standard rounding: 0.02
>Accountant rounding: 0.02
>
>This looks like a "just plain wrong" result to me.  If you don't care about
>the least significant digit, this might be tolerable for you.
>
>> >>>> foo(5, 200)
>> > '0.03'
>
>Standard rounding: 0.03
>Accountant rounding: 0.02
>
>Again, the result resembles what you get with standard rounding.  This case
>doesn't really demonstrate anything new.
>
>> >>>> foo(10000000000000000000000000000000000000000l, 2)
>> > '5000000000000000200000000000000000000000.00'
>                     ^
>Not just incorrect, but the incorrect digit is right in the middle of the
>number, not in the least significant place.

In all cases you show above, the output from the "%" operator appears
correct to me. AFAICT, the FP results are all correct also.

What you are calling "unreliable" seems to be standard IEEE FP behavior.

The OP stated that float(a)/b was fine, and he wanted a way to format the FP
result of that expression.  The OP was told he could use "%.2f" to format
his results.  That's the simplest way to do what he asked, and AFAICT it
produces correct results.

You seem to be telling the OP that he's wrong, float(a)/b isn't good enough,
and he shouldn't be using floating point?

-- 
Grant Edwards                   grante             Yow!  for ARTIFICIAL
                                  at               FLAVORING!!
                               visi.com            



More information about the Python-list mailing list