How to write string (float) to file?
Bengt Richter
bokr at accessone.com
Tue Aug 28 17:11:25 EDT 2001
On Tue, 28 Aug 2001 15:41:57 GMT, "Rainer Deyke" <root at rainerdeyke.com> wrote:
><gbreed at cix.compulink.co.uk> wrote in message
>news:9mfqmi$ko4$1 at thorium.cix.co.uk...
>> In article <9mfm1l$gs3$1 at zeus.man.szczecin.pl>,
>> piotrlg at sci.pam.szczecin.pl (Piotr Legiecki) wrote:
>>
>> > How can I tell python to give me only 2 digits after decimal point? And
>> > of course store it in a variable.
>> >
>> > So I want 'c' to be 3.33.
>>
>> c = '%.2f'%(float(a)/b)
>
>That's unreliable. Use this instead:
Unreliable in what sense?
>
>c = (a * 100) / b
>s = '%03d' % c
>file.write(s[:-2] + '.' + s[-2:])
>
Making a function of your logic:
>>> def foodiv(a,b):
... c = (a * 100) / b
... s = '%03d' %c
... return s[:-2] + '.' + s[-2:]
...
>>> for x in [30,-30,60,-60]: print foodiv(x,9)
...
3.33
-3.34
6.66
-6.67
Is that the reliable results you think he wants? ;-)
Whereas
>>> for x in [30,-30,60,-60]: print '%.2f'%(float(x)/9)
...
3.33
-3.33
6.67
-6.67
You shouldn't mess with newbie minds like that ;-)
More information about the Python-list
mailing list