How to limit number of decimal places

Hello!

I would like to know how I would be able to limit the number of decimals shown during the following exercise: https://www.codecademy.com/courses/learn-python-3/projects/python-furniture-store

My code is:

lovely_loveseat_description = "Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide x 30 inches deep. Red or white. "

lovely_loveseat_price = 254.00

stylish_settee_description = "Stylish Settee. Faux leather on birch. 29.50 inches high x 54.75 inches wide x 28 inches deep. Black. "

stylish_settee_price = 180.50

luxurious_lamp_description = "Luxurious Lamp. Glass and iron. 36 inches tall. Brown with cream shade. "

luxurious_lamp_price = 52.15

sales_tax = 0.088

#----------

customer_one_total = 0

customer_one_itemization = " "

#Customer 1 bought Lovely Loveseat

customer_one_total += lovely_loveseat_price

customer_one_itemization += "• " + lovely_loveseat_description

#Customer 1 bought Luxurious Lamp

customer_one_total += luxurious_lamp_price

customer_one_itemization += "• " + luxurious_lamp_description

#Customer 1 checks out

customer_one_tax = customer_one_total * sales_tax

customer_one_total += customer_one_tax

#Customer 1 receipt:

print("Customer One Items: ")

print(customer_one_itemization)

print("Customer One Total: ")

print(" ", customer_one_total)

Which gives the final total of 333.09119999999996

I would like that the final total only shows 333.09, how would I be able to do this?

Thank you!

The round function is quite nice for this- https://docs.python.org/3/library/functions.html#round

Alternatively formatting the value in a string is quite handy too, for example:

x = 333.09119999999996
print(f"{x:.2f}")
Out: 333.09

See the following for some details on string formatting options-
This link is directed towards python2 but the various formatting options (padding, truncation etc.) are covered nicely https://pyformat.info/

A brief introduction to various formatting options with 3.6+: https://realpython.com/python-string-formatting/

For more in-depth info (more options but more complex): https://docs.python.org/3/library/string.html#formatspec

As a further option you could change your values so you are working with integers instead. Then you avoid losing accuracy from floating point arithmetic issues- 15. Floating Point Arithmetic: Issues and Limitations — Python 3.9.4 documentation.

4 Likes