In Development Last updated:
Share on:
Cloudways offers managed cloud hosting for any size business to host a website or complex web applications.

Working with numeric data types in Python? Level up by learning the different ways to round numbers in Python.

Most real-world dataset contains numeric as well as categorical features. There is a broad array of numeric features, from sensor readings to currency exchange rates, biomedical signals, and more.

When working with numeric values, you may need to round these values to a fixed precision for reasons such as:

  • Ensuring a consistent format
  • Easier storage and processing

In this tutorial, we’ll learn the different ways to round a number to a specific precision, round up and round down numbers to the nearest integer, and much more.

Let’s get started.

How to Round Numbers Using the Built-in round() Function

The most common method to round numbers in Python is using the built-in round() function. Let’s start by learning its syntax:

round(num, ndigits)

Here,

  • num is the number that you want to round 
  • ndigits is an optional parameter with a default value of None. It is the number of places to round the number to. If ndigits = 2, num is rounded to two places after the decimal point.
  • The round() function returns num rounded to ndigits precision after the decimal point.

Python round() Function Usage Examples

Let’s code some examples to understand how the round() function works.

As mentioned, ndigits is optional. So when we call round() with only the number, the number is rounded to the nearest integer.

number = 7.123456
rounded = round(number)  
print(rounded)
# Output: 7

Now let’s take some examples where we specify the precision.

With ndigits set to 2, number is rounded to two decimal places (tenth place):

number = 7.123456
rounded = round(number, 2)  
print(rounded)
# Output: 7.12

With ndigits set to 3, number is rounded to three decimal places (hundredth place):

number = 7.123456
rounded = round(number, 3)  
print(rounded)
# Output: 7.123

You can use round() to round negative numbers as well:

number = -3.4
rounded = round(number)
print(rounded) 
# Output: -3

Here, the function rounds -3.4 to -3, the nearest integer.

Rounding to the Nearest Tens and Hundreds Place

Did you know that ndigits can also take negative values?

Yes, you can call the round() function with negative values for ndigits. When you do so, the rounding happens to the left of the decimal point instead of the right.

What does this mean? Let’s see some examples.

When we set ndigits to -1, the number is rounded to the nearest tens place.

number = 7.123456
rounded = round(number, -1)  
print(rounded)
# Output: 10.0

And calling the round() function with ndigits set to -2 rounds up the number 77.123456 to the nearest hundred, which in this case is 100.0.

number = 77.123456
rounded = round(number, -2)  
print(rounded)
# Output: 100.0

So far, the round() function seems to follow the general principles of rounding that we’ve learned in school math. But that’s not always the case. 

There are some limitations with floating point numbers. So you may see some unexpected results when rounding. Another interesting caveat is the banker’s rounding.

What Is Banker’s Rounding?

Start a Python REPL and try the following example:

>>> round(1.5)
2

We see that round(1.5) returns 2 (as expected). So what should round(2.5) return?

>>> round(2.5)
2

Interesting, yes? Both round(1.5) and round(2.5) return 2. But how and why?

Internally, the round function works like so: any value that is midway between two integers is rounded to the nearest even integer. This is called banker’s rounding or the round half to even strategy.

We know that the round() function suffices for simple rounding tasks. But sometimes, you may need to round up or round down a number to the nearest integer.

So how do you do that? Let’s learn that in the next section.

How to Round Up Numbers in Python

To round up a number to the nearest integer, you can use:

  • The ceil() function from the math module or 
  • The decimal module

Using math.ceil

 The ceil() function (or ceiling function) works like so: It rounds up a number to the smallest integer that is greater than the number.

The following snippet shows how to use the ceil() function to round up the number 3.2:

import math

number = 3.2
rounded_up = math.ceil(number)
print(rounded_up)  
# Output: 4

Using the Decimal Module

So far, we’ve used the built-in float data type. But for certain applications in scientific computing and finance, we need much higher precision. And for this, Python ships with the decimal module that provides:

  • More precise floating point arithmetic 
  • Reliable equality testing
  • Finer control over the precision level (the default precision is 28 places)

To see the current context, using getcontext() as shown:

from decimal import getcontext
current_context = getcontext()
print(current_context)

You should be able to see the current precision and rounding mode, amongst others:

# Output
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, 
capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

To round up a number, you can use quantize() by specifying:

  • The precision (0.0 since we want to round up to the nearest integer) and
  • The rounding mode: ROUND_CEILING
from decimal import Decimal, ROUND_CEILING

number = Decimal('3.2')
rounded_up = number.quantize(Decimal('0'), rounding=ROUND_CEILING)
print(rounded_up)  
# Output: 4

Here, the number 3.2 has been rounded up to the nearest integer 4.

How to Round Down Numbers in Python

Now, let’s see how to round down numbers in Python. Similar to the rounding-up process, we can use either the math or the decimal modules.

Using math.floor

The floor() function from the math module works like so: It rounds down a number to the greatest integer that is smaller than the number.

Let’s take the following example:

import math

number = 3.8
rounded_down = math.floor(number)
print(rounded_down)  
# Output: 3

Here, the floor() function rounds down the floating-point number 3.8 to 3.

Using the Decimal Module

To round down a number, you can use quantize() by setting the rounding mode to ROUND_FLOOR.

from decimal import Decimal, ROUND_FLOOR

number = Decimal('3.8')
rounded_down = number.quantize(Decimal('0'), rounding=ROUND_FLOOR)
print(rounded_down)  
# Output: 3

As seen, 3.8 has been rounded down to 3.

Common Pitfalls to Avoid When Rounding Numbers

We’ve already seen that the round() function rounds half to even, which may not always be desired. There are some other common pitfalls to avoid when rounding numbers in Python:

  • Incorrect equality comparison: Rounding numbers often introduce rounding errors. If you try to perform an equality comparison between a rounded result with another value, the equality check will (almost always) fail due to varying precision. So try to avoid equality checks between floating point and rounded floating point numbers. If the comparison is necessary, then introduce a tolerance threshold.
  • Loss of information: You may want certain data like sensor readings at different time stamps captured in high precision. Rounding such data to fewer decimal places results in loss of information and incorrect analysis. 
  • Rounding intermediate results: You’ll often have multiple steps as part of the computation. Use consistent precision across all the steps. Also, avoid rounding at intermediate steps to prevent the rounding errors from compounding.

Best Practices to Round Numbers in Python

Let’s list some best practices to follow when rounding numbers in Python:

  • Choose the right data type: Choose between float and decimal data types depending on the application. If you need to perform high-precision floating point arithmetic, choose decimal data type.
  • Use consistent precision levels: Set consistent precision levels for decimal numbers throughout the entire program to avoid unexpected rounding errors.
  • Document rounding techniques: In real-world applications involving data like currency and sensor readings it is important to have a consistent and documented rounding technique in place.

Wrapping Up

Let’s wrap up the tutorial with a quick review of what we’ve learned:

  • You can use the built-in round() function with this syntax round(num, ndigits). When using the round() function, you should be aware of the banker’s rounding strategy. So, it rounds numbers exactly between two integers to the nearest even integer.
  • You can use the ceil() and floor() functions from the math module to round up and round down a given number to the nearest integer, respectively.
  • When you need to perform high-precision floating-point arithmetic, use the decimal module. You can round numbers with the required precision and rounding strategy. 
  • You should be aware of common pitfalls with rounding numbers in Python. These include loss of information from rounding, rounding results at intermediate steps, and using different precision in different parts of the code.
  • Best practices include choosing the right data type depending on the application and documenting consistent precision levels. 

Next, learn how to perform floor division in Python.

Share on:
  • Bala Priya C
    Author
    Bala Priya is a developer and technical writer from India with over three years of experience in the technical content writing space. She shares her learning with the developer community by authoring tech tutorials, how-to guides, and more….
  • Rashmi Sharma
    Editor

    Rashmi is a highly experienced content manager, SEO specialist, and data analyst with over 7 years of expertise. She has a solid academic background in computer applications and a keen interest in data analysis.


    Rashmi is…

Thanks to our Sponsors

More great readings on Development

Power Your Business

Some of the tools and services to help your business grow.
  • The text-to-speech tool that uses AI to generate realistic human-like voices.

    Try Murf AI
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.

    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.

    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.

    Try Intruder