round()
The built-in round() function takes a numeric argument and returns it rounded to a specified number of decimal places. For the built-in numeric types, this rounding operation uses the round half-to-even strategy, which can yield results that may initially seem counterintuitive, such as rounding 2.5 to 2:
>>> round(2.5)
2
round() Signature
round(number, ndigits=None)
Arguments
Return Value
- Returns a number rounded to the specified number of decimal places.
- Returns an integer if
ndigitsis omitted orNone. Otherwise, the return value has the same type asnumber. For example, rounding a floating-point number returns a float, even whenndigitsis zero or negative. - For any other object,
round()delegates to that object’s__round__()method, so custom classes can support rounding by implementing it.
round() Examples
With a single argument to round to the nearest integer:
>>> round(1.5)
2
With two arguments to round to one decimal place:
>>> round(1.64, 1)
1.6
round() Common Use Cases
The most common use cases for the round() function include:
- Rounding floating-point numbers for presentation purposes.
- Rounding monetary values for display, though exact monetary arithmetic calls for the
decimalmodule. - Reducing the precision of floating-point arithmetic results.
round() Real-World Example
Suppose you’re handling a list of product prices and want to round them to two decimal places for display on a web page:
>>> prices = [19.995, 20.005, 10.5, 5.678]
>>> rounded_prices = [round(price, 2) for price in prices]
>>> rounded_prices
[20.0, 20.0, 10.5, 5.68]
In this example, round() helps you format the prices to two decimal places, making them suitable for display in a financial context.
Related Resources
Tutorial
How to Round Numbers in Python
In this tutorial, you'll learn what kinds of mistakes you might make when rounding numbers and how you can best manage or avoid them. It's a great place to start for the early-intermediate Python developer interested in using Python for finance, data science, or scientific computing.
For additional information on related topics, take a look at the following resources:
- Rounding Numbers in Python (Course)
- Python Built-in Functions: A Complete Guide (Tutorial)
- Numbers in Python (Tutorial)
- Rounding Numbers in Python (Quiz)
- Exploring Python's Built-in Functions (Course)
- Python Built-in Functions: A Complete Guide (Quiz)