[Tutor] Rounding Error

Alan Gauld alan.gauld at btinternet.com
Sat Jan 28 09:03:19 CET 2012


On 28/01/12 05:55, Michael Lewis wrote:
> I am trying to round a float to two decimals, but I am getting the
> following error:
>
> Traceback (most recent call last):
>    File "<pyshell#23>", line 1, in <module>
>      PaintingProject()
>    File "C:/Python27/Homework/Labs/Lab 03_5.py", line 42, in PaintingProject
>      print 'That will cost you $%f.' %(round(5.6523),2)
> TypeError: not all arguments converted during string formatting
>

In general rounding the float is the wrong approach, instead you want to 
display the float with two decimal places. You can do that with options 
in the format string. Try:

       print 'That will cost you $%4.2f.' % 5.6523)

The %4.2f says use 4 characters with 2 of them after the decimal point.
There are many other options you can use to tweak the display, read the 
string formatting documents...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list