How to Round Numbers with f-strings in Python

Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.

Easy Python 3.6+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

26 lines
Python 3.6+
def main():
    # Values to format with expression-based rounding
    price = 19.995
    tax_rate = 0.0825
    distance = 1234.56789

    # Round inside the f-string expression using round()
    print(f"Price rounded to cents: ${round(price, 2)}")

    # Combine rounding with arithmetic inside the expression
    total = price * (1 + tax_rate)
    print(f"Total with tax rounded: ${round(total, 2)}")

    # Round to nearest whole number using expression
    print(f"Distance rounded to meters: {round(distance)} m")

    # Round down (floor) and up (ceil) using expressions
    print(f"Floor of price: {int(price)}")
    print(f"Ceil of price: {int(price) + 1 if price != int(price) else int(price)}")

    # Format with rounding and zero-padding in one expression
    print(f"Padded rounded value: {round(distance, 1):08.1f}")


if __name__ == "__main__":
    main()

Output

stdout
Price rounded to cents: $20.0
Total with tax rounded: $21.64
Distance rounded to meters: 1235 m
Floor of price: 19
Ceil of price: 20
Padded rounded value: 0001234.6

How it works

F-strings allow you to embed any Python expression inside curly braces, including function calls like round(). The round() function can take two arguments: the number and the number of decimal places. When no precision is given, round() returns the nearest integer. F-strings evaluate the expression at runtime, so you can combine arithmetic operations and formatting specifiers in one compact expression. This approach keeps formatting logic inline with the output, making the code more readable and maintainable.

Common mistakes

  • Forgetting that round() uses banker's rounding (rounds .5 to even numbers)
  • Trying to apply format specifiers like :.2f inside round(), which causes a TypeError
  • Assuming round() with one argument returns a float instead of an int

Variations

  1. Use format() method: print('{:.2f}'.format(round(price, 2)))
  2. Use Decimal from the decimal module for currency with exact decimal arithmetic

Real-world use cases

  • Formatting currency values for receipts and invoices where exact cents matter
  • Displaying sensor or measurement data rounded to useful precision in dashboards
  • Creating human-friendly log messages with precise-but-readable numeric values

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.