Round to 2 decimal places

Steve D'Aprano steve+python at pearwood.info
Wed Dec 6 21:43:06 EST 2017


On Thu, 7 Dec 2017 11:58 am, nick martinez wrote:

> I'm stuck. I need my program to round the end solution to 2 decimal places
> but cant figure it out. Can someone help? I've been trying between printf
> and round() but cant seem to get either to work.

It might help if you show exactly what values you have tried. This works for
me:

py> volume = 1.23456789
py> print(volume )
1.23456789
py> print(round(volume , 2))
1.23

The rest of your code is interesting but irrelevant to your question. If you
want to learn how to round to 2 decimal places, the actual calculation of
surface area and volume aren't necessary. The only really important part is
this line:

>    print("A cone with radius", r, "\nand height of", h, "\nhas a volume of :
>    ", volume, "\nand surface area of : ", surfacearea,)


and even that can be cut down to just:

volume = 2345.987654321  # for example
print(volume)


We can round the result first, then print it:


print(round(volume, 2))


or we can change the display by using string formatting:


print("%.2f" % volume)

print("{:.2f}".format(volume))



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list