[Tutor] Format strings for variables - how?

Lindsay Davies Lindsay.Davies@moonshine.co.uk
Thu, 8 Feb 2001 08:48:11 +0000


--============_-1230500353==_ma============
Content-Type: text/plain; charset="us-ascii" ; format="flowed"

On 8/2/01, David Porter wrote about 'Re: [Tutor] Format strings for 
variables - how?':
>  > a=1
>>  b=3
>>  print "%0.2f" %(a/b)
>>
>>  The above code gives me 0.00 as a result, while I wanted to get
>>  0.33...
>
>The reason is that the numbers you are dividing are not floats. Because of
>that, you are doing integer division.
>
>>>>  a = 1.0
>>>>  b = 3
>print "%0.2f" %(a/b)
>
>gives 0.33. You must add a decimal point to one (or more) of the numbers.

...or alternatively make the variable type explicit...

a = float(1)
b = float(3)
print "%0.2f" %(a/b)


Best wishes,

Lindsay
--============_-1230500353==_ma============
Content-Type: text/html; charset="us-ascii"

<!doctype html public "-//W3C//DTD W3 HTML//EN">
<html><head><style type="text/css"><!--
blockquote, dl, ul, ol, li { margin-top: 0 ; margin-bottom: 0 }
 --></style><title>Re: [Tutor] Format strings for variables -
how?</title></head><body>
<div>On 8/2/01, David Porter wrote about 'Re: [Tutor] Format strings
for variables - how?':</div>
<blockquote type="cite" cite>&gt; a=1<br>
&gt; b=3<br>
&gt; print &quot;%0.2f&quot; %(a/b)<br>
&gt;<br>
&gt; The above code gives me 0.00 as a result, while I wanted to
get<br>
&gt; 0.33...<br>
</blockquote>
<blockquote type="cite" cite>The reason is that the numbers you are
dividing are not floats. Because of<br>
that, you are doing integer division.<br>
<br>
&gt;&gt;&gt; a = 1.0<br>
&gt;&gt;&gt; b = 3<br>
print &quot;%0.2f&quot; %(a/b)<br>
</blockquote>
<blockquote type="cite" cite>gives 0.33. You must add a decimal point
to one (or more) of the numbers.</blockquote>
<div><br></div>
<div>...or alternatively make the variable type explicit...</div>
<div><br></div>
<div><font color="#000000">a = float(1)<br>
b = float(3)</font></div>
<div><font color="#000000"><b>print</b></font><font color="#007F00">
&quot;%0.2f&quot;</font><font color="#000000"> %(a/b)</font></div>
<div><br></div>
<div><br></div>
<div>Best wishes,</div>
<div><br></div>
<div>Lindsay</div>
</body>
</html>
--============_-1230500353==_ma============--