round()
The built-in round()
function takes a numeric argument and returns it rounded to a specified number of decimal places. 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
Argument | Description | Default Value |
---|---|---|
number |
The number to be rounded. | Required argument |
ndigits |
The number of decimal places to round to. If omitted, it rounds to an integer. | None |
Return Value
- Returns a number rounded to the specified number of decimal places.
- With integer values for
ndigits
, it returns a floating-point number ifndigits
is greater than zero. Otherwise, it returns an integer.
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 to a fixed number of decimal places.
- 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 webpage:
>>> prices = [19.995, 20.005, 10.5, 5.678]
>>> rounded_prices = [round(price, 2) for price in prices]
>>> rounded_prices
[20.0, 20.01, 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:
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- Numbers in Python (Tutorial)
- Rounding Numbers in Python (Course)
- Rounding Numbers in Python (Quiz)
- Python's Built-in Functions: A Complete Exploration (Quiz)