[Tutor] Help on float & round.

Alfred Milgrom fredm@smartypantsco.com
Wed Jun 11 00:53:04 2003


At 11:13 PM 10/06/03 -0500, Decibels wrote:
>Hello,
>
>         New to the list and having a problem with float & round or my 
> lack of understanding.
>
>Basic: I am getting stock prices, it puts it in a list, then I convert it 
>to strings, floating and integers.
>The problem I am having is that it converts the string to a float fine. 
>But rounding it off and saving
>it as a variable isn't working like I expected.
>
>Examples:
>
>         # Original number before conversion was 70.70 as string.
>         # I get the 3rd item of the list called stock. And rightly so it 
> will print like this.
>         print "Current Price: %f" % (stock[2])
>         ......
>results:  Current Price: 70.700000
>
>What I want is for it to print at 70.70, but not be a string, but a float for
>math purposes.
><snip>


 From your example, it seems you are doing things correctly but not using 
the full power of %f.

%f will include the variable into the string in floating-point form, but 
you can also specify the total length of the number and the number of 
decimal points. For example "%4.1f" will display up to 4 characters, one of 
which will be after the decimal point.

 >>> stock=['today', 'somestock', 70.7]
 >>> "Current Price: %4.2f" % (stock[2])
'Current Price: 70.70'

If your number has more than 2 digits, the %f formatting will round it out 
correctly (rather than truncate):

 >>> stock=['today', 'somestock', 70.7285]
 >>> "Current Price: %4.2f" % (stock[2])
'Current Price: 70.73'

Hope this helps,
Fred Milgrom




>