[Tutor] Rounding Error

Steven D'Aprano steve at pearwood.info
Sat Jan 28 07:20:20 CET 2012

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

> Basically, I am writing a program to ask a user how many square feet they
> need to paint.

All this is irrelevant to your problem. Read the error message: it says that 
you have more arguments than expected when doing the string formatting. 
round() doesn't enter into it. You can get the same error if you do this:

print 'That will cost you $%f.' % (5.6523, 2)

You have one % target in the string, but two numbers trying to fit into it, 
and Python refuses to guess if you want to use 5.6523 or 2.

And that should give you the clue you need to solve the problem, which brings 
it back to round(). You want to round to two decimal places, but you don't put 
the 2 inside the call to round. You have:

(round(5.6523), 2)

which gives you two numbers: (6.0, 2)

but what you actually want is:

round(5.6523, 2)

which gives you the number you want, 5.65.

And finally, we come all the way back to the beginning again and say That's 
not the right way to do it! Don't round the number *outside* of the string 
formatting, get the string formatting to do it for you:

print 'That will cost you $%.2f.' % 5.6523

will give you the result you want.


More information about the Tutor mailing list