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:

Python
>>> round(2.5)
2

round() Signature

Python Syntax
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 if ndigits is greater than zero. Otherwise, it returns an integer.

round() Examples

With a single argument to round to the nearest integer:

Python
>>> round(1.5)
2

With two arguments to round to one decimal place:

Python
>>> 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:

Python
>>> 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.

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.

intermediate best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 7, 2024 • Reviewed by Dan Bader