How to write string (float) to file?
Jeff Shannon
jeff at ccvcorp.com
Tue Aug 28 14:07:46 EDT 2001
Rainer Deyke wrote:
> <gbreed at cix.compulink.co.uk> wrote in message
>
> > c = '%.2f'%(float(a)/b)
>
> That's unreliable. Use this instead:
>
> c = (a * 100) / b
> s = '%03d' % c
> file.write(s[:-2] + '.' + s[-2:])
>
Unreliable how?
>>> l1 = [5, 13, 23, 30, 42, 86, 101, 153, 999, 123456]
>>> l2 = [2, 5, 23, 59]
>>> def foo(a, b):
... return '%.2f' % (float(a)/b)
...
>>> def bar(a, b):
... s = '%03d' % ( (a*100)/b )
... return s[:-2] + '.' + s[-2:]
...
>>> for b in l2:
... for a in l1:
... x, y = foo(a,b), bar(a,b)
... full = repr(float(a)/b)
... print '%10s %10s %d %s' % (x, y, (x==y), full)
...
2.50 2.50 1 2.5
6.50 6.50 1 6.5
11.50 11.50 1 11.5
15.00 15.00 1 15.0
21.00 21.00 1 21.0
43.00 43.00 1 43.0
50.50 50.50 1 50.5
76.50 76.50 1 76.5
499.50 499.50 1 499.5
61728.00 61728.00 1 61728.0
1.00 1.00 1 1.0
2.60 2.60 1 2.6000000000000001
4.60 4.60 1 4.5999999999999996
6.00 6.00 1 6.0
8.40 8.40 1 8.4000000000000004
17.20 17.20 1 17.199999999999999
20.20 20.20 1 20.199999999999999
30.60 30.60 1 30.600000000000001
199.80 199.80 1 199.80000000000001
24691.20 24691.20 1 24691.200000000001
0.22 0.21 0 0.21739130434782608
0.57 0.56 0 0.56521739130434778
1.00 1.00 1 1.0
1.30 1.30 1 1.3043478260869565
1.83 1.82 0 1.826086956521739
3.74 3.73 0 3.7391304347826089
4.39 4.39 1 4.3913043478260869
6.65 6.65 1 6.6521739130434785
43.43 43.43 1 43.434782608695649
5367.65 5367.65 1 5367.652173913043
0.08 0.08 1 0.084745762711864403
0.22 0.22 1 0.22033898305084745
0.39 0.38 0 0.38983050847457629
0.51 0.50 0 0.50847457627118642
0.71 0.71 1 0.71186440677966101
1.46 1.45 0 1.4576271186440677
1.71 1.71 1 1.7118644067796611
2.59 2.59 1 2.593220338983051
16.93 16.93 1 16.932203389830509
2092.47 2092.47 1 2092.4745762711864
>>>
The bar() version, your suggestion, appears to *usually* truncate, but in a few
cases rounds up. The foo() version *always* rounds to nearest .01. I would
consider the latter to be the more reliable (consistent) behavior. (I was
surprised by this, actually--I expected bar() to always truncate, and was going
to simply point out that it was a matter of whether truncation or rounding was
preferred...)
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list