Skip to main content

How to Show a Number with Two Decimal Places in a Python f-string

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Prices, scores and percentages read better with a fixed number of decimals: 3.14 instead of 3.14159, and 2.50 instead of 2.5. Inside an f-string, :.2f after the value does it. This guide shows it on Python 3.15.2.

Syntax​

Syntax
f"{<number>:.<digits>f}"
PartWhat it means
<number>The value to show, such as a variable
:Starts the format specification: how to show the value
.<digits>How many digits after the decimal point, such as .2
fFixed-point notation: a plain decimal number

The format specification documentation defines f as "Fixed-point notation. For a given precision p, formats the number as a decimal number with exactly p digits following the decimal point."

The Example​

Two prices: one with too many decimals, one with too few. Both should print with exactly two.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

decimals.py
price = 3.14159
print(f"Price: {price:.2f}")
print(f"Price: {2.5:.2f}")

The decimals.py script in a macOS-style code window: price set to 3.14159 and printed with :.2f, then 2.5 printed with :.2f.

Step 2: Run It​

Terminal
uv run python decimals.py
Output
Price: 3.14
Price: 2.50

The terminal after uv run python decimals.py: Price: 3.14, then Price: 2.50.

3.14159 was rounded to two digits, and 2.5 got a zero added, so both have exactly two. The variable itself didn't change: only the text did. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Formatting text that only looks like a number: f"{'3':.2f}"ValueError: Unknown format code 'f' for object of type 'str'Convert it first: f"{float(text):.2f}"
Expecting 2.675 to show as 2.68f"{2.675:.2f}" gave 2.67: the number stored for 2.675 is a tiny bit smaller than 2.675, because computers store most decimals as close binary fractionsFor money, keep amounts as whole cents or use the decimal module
Writing .2 without the fPython keeps two significant digits instead of two decimals: f"{3.14159:.2}" gave 3.1, and f"{1234.5678:.2}" gave 1.2e+03Keep the f: :.2f

FAQ​

Does it work for whole numbers?​

Yes. f"{3:.2f}" gave 3.00.

How do I add a thousands separator too?​

Put a comma before the dot: f"{1234.5678:,.2f}" gave 1,234.57.

Conclusion​

:.2f showed 3.14159 as 3.14 and 2.5 as 2.50: always two digits after the decimal point, without changing the number itself.

Additional Resources​