Printing in Python - Formatting numbers and rounding

 A few convenient Python print tips this time around:


When printing/displaying floats (decimals) in Python, you can use the f function to do some cleaner printing.

Say for example you have a number that is three or more decimal places (precision) such as:

cost = 29.9853

You can print the entire value with the simple print statement:

print(cost)

But if you want to show the value with only two places, you can do print it like this, keeping in mind that the value displayed will be rounded up or down depending on the portion that will not be displayed.

print(f"The cost is ${cost:.2f}")


Notice the syntax. Its a bit cumbersome, because of the nesting.

To round to two decimals use this syntax and remember that dot before the decimal precision you want to use.

{variable name:.2f}






Comments