Formatting Numbers
In this tutorial, we'll display decimals, money-like values, and percentages neatly.
F-strings can also control how numbers appear.
This is especially useful for decimals:
price = 4.999
print(f"Price: {price}")
Output:
Price: 4.999
You may want two decimal places instead.
Decimal Places
Use :.2f for two decimal places:
price = 4.999
print(f"Price: {price:.2f}")
Output:
Price: 5.00
The f means fixed-point number. The .2 means two decimal places.
Money-Like Output
price = 12.5
quantity = 3
total = price * quantity
print(f"Total: £{total:.2f}")
Output:
Total: £37.50
Percentages
Use :.1% to display a decimal as a percentage:
success_rate = 0.875
print(f"Success: {success_rate:.1%}")
Output:
Success: 87.5%
Common Mistake
Formatting changes how a number is displayed. It does not change the original value:
number = 3.14159
print(f"{number:.2f}")
print(number)
The second print still shows the original number.
Store the Formatted Text
If you need the formatted version later, store it in a variable:
price = 4.5
display_price = f"£{price:.2f}"
print(display_price)
display_price is now a string. Use it for showing output, not for further maths.
Practice
Create a subtotal and tax rate. Print the tax and total with two decimal places.