← All lessons

Lesson 23

Formatting Numbers

Inside an f-string, add a format spec after a colon: {price:.2f} shows exactly two decimals.

Use {n:05d} to pad with zeros, {n:,} for thousands separators, and {ratio:.0%} to show a percentage.

Formatting changes only the displayed text. The underlying number keeps its full precision.

price = 4.5
print(f"${price:.2f}")
print(f"{1234567:,}")

Check your understanding

What does f"{3.14159:.2f}" produce?

CHALLENGE

Set total to 1234.5. Print it as dollars with a thousands separator and two decimals, like $1,234.50.

Practice →
Next: Recursion →