← Python lessons

Python Number Formatting: Decimals, Commas, % and Alignment

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A format specifier controls how an f-string shows a number: decimal places, width, alignment and separators. It goes after a colon, as in {price:.2f}.

Read String Formatting first. The later examples also use try and except, and the task loops over pairs with unpacking.

Show two decimal places

:.2f shows a number with exactly two digits after the decimal point.

price = 3.5
print(f"Price: ${price:.2f}")
print(price)

The first line is Price: $3.50. The second is 3.5: formatting makes text for display and does not change price.

Format or round()?

round() changes the number. A format specifier only changes how it looks. Use round() when you will keep calculating, and :.2f when you print.

total = 12.5
print(round(total, 2))
print(f"{total:.2f}")

round(total, 2) prints 12.5, because the number has no second digit to show. Only :.2f guarantees 12.50.

Line up columns with width and alignment

A number before the type sets the width: the minimum number of characters. < aligns left, > aligns right and ^ centres.

print(f"[{'Ada':<6}][{8:>4}]")
print(f"[{'Sam':<6}][{12:>4}]")
print(f"[{'hi':^6}]")

The brackets show the padding. Names line up on the left and scores on the right. The order inside the braces is alignment, width, then decimals: {price:>8.2f} means right-aligned, 8 wide, two decimal places.

Thousands separators and percentages

, adds a comma every three digits. % multiplies by 100 and adds a percent sign.

crowd = 1250000
win_rate = 0.375
print(f"{crowd:,} people")
print(f"Win rate: {win_rate:.1%}")

This prints 1,250,000 people, then Win rate: 37.5%.

When a specifier does not fit the value

A number specifier needs a number. Text read from input() is a string, so convert it first.

amount = "4.5"
try:
    print(f"{amount:.2f}")
except ValueError as error:
    print("Error:", error)
print(f"{float(amount):.2f}")

The first attempt raises ValueError. After float() it prints 4.50.

Note: This lesson covers the common specifiers. The full format mini-language also has fill characters, signs and other number bases.

See also: Data Validation.

Your turn

Print each item on its own line: the name left-aligned in 8 characters, then the price right-aligned in 7 characters with two decimal places.

items = [("Pie", 4.5), ("Coffee", 12), ("Cake", 3.25)]
for name, price in items:
    print(name, price)  # change this to use width, alignment and :.2f

Expected output

Pie        4.50
Coffee    12.00
Cake       3.25