Skip to content

Round Number to the Nearest Multiple in Python (2, 5, 10, etc.)

How to Round to Nearest Multiple of a Number in Python Cover Image

In this tutorial, you’ll learn how to use Python to round a number to a nearest multiple, such as the nearest 2, 5, or 10. Being able to round numbers is a helpful skill, as it often makes them easier to understand and to use. Python makes it simple to round a number up or down, but rounding to a particular interval is a different story.

In fact, this is possibly something that is easier to do in Excel. Excel provides a function MROUND(), which rounds a number to the closest interval passed in as a parameter. By the end of this tutorial, you’ll have learned how to emulate the behaviour of the MROUND() function, by learning how to use Python to round a number to a given interval.

You’ll learn how to round to a number of predefined intervals, such as 2 and 5, as well as to 10 or any multiplier of ten. You’ll also learned how to develop your own function that allows you to pass in an interval and round a number to the closest interval value.

The Quick Answer: Use multiple * (number / multiple)

Quick Answer - Python Round a Number to a Multiple

Rounding Numbers in Python: A Quick Recap

Python does provide a function that allows you to round a number, the round() function. The function is part of the normal Python library, meaning that you don’t need to import anything. The function accepts two parameters: (1) a number (either an integer or a floating point value), and (2) the number of decimals to which to round the number.

While this function is particularly helpful in rounding a number, it does not give you the option to round a number to a given interval. For example, the round() function would allow you to round to the nearest whole number (i.e., an interval of 1), it would not allow you to round the nearest interval of, say, 5.

So, say we wanted to round a number to its nearest whole number, we could use the round() function. Let’s see what this looks like:

# Using the round() function to round a number in Python
number1 = 1.55
number2 = 33.67

rounded1 = round(number1, 0)
rounded2 = round(number2, 0)

print('rounded1 = ', rounded1)
print('rounded2 = ', rounded2)

# Returns:
# rounded1 =  2.0
# rounded2 =  34.0

Similarly, Python provides functions via the math library to allow you to either round a value up or down. The math.floor() function is used to round a number down, while the math.ceil() function is used to round a number up.

In the following section, you’ll learn how to develop a custom function that allows you to round to a given multiple in Python.

Want to learn how to round values in a Pandas DataFrame? Check out this guide to rounding values in Pandas, including rounding values down.

Developing a Custom Function to Round to a Multiple in Python (e.g., 2, 5, etc.)

Because Python doesn’t come built-in with a function that allows us to round a number to a given multiple, it may be helpful to build your own. This is what you’ll learn in this section of the tutorial.

Why do we want to build functions? Functions allow us to follow the programming DRY ethos, meaning “don’t repeat yourself”. This means that we can re-use functions throughout our code. While the code the function will take is relatively straightforward, developing a function also allows our code to be more readable. Readability is an important skill in troubleshooting your code. It also allows future readers to better understand what it is you’re hoping to accomplish.

Let’s see how we can use Python to develop a function to round a given number to an interval:

# Developing a function to round to a multiple
def round_to_multiple(number, multiple):
    return multiple * round(number / multiple)

# Rounding 23 to a multiple of 5
print(round_to_multiple(23, 5))
# Returns 25

# Rounding 121 to an interval of 100
print(round_to_multiple(121, 100))
# Returns 100

Let’s break down what we’ve done here:

  1. We define a function that takes two parameters, the number we want to round and the multiple to which we want to round it
  2. We then return the multiple multiplied by the rounded quotient between the number and the multiple

We can take this one step further, however. We can customize our function to take a third parameter to indicate that we want to round down, up, or to the nearest multiple.

# Developing a function to round to a multiple
from math import ceil, floor
def round_to_multiple(number, multiple, direction='nearest'):
    if direction == 'nearest':
        return multiple * round(number / multiple)
    elif direction == 'up':
        return multiple * ceil(number / multiple)
    elif direction == 'down':
        return multiple * floor(number / multiple)
    else:
        return multiple * round(number / multiple)

# Rounding 23 to a multiple of 5
print(round_to_multiple(23, 5, 'nearest2'))
print(round_to_multiple(23, 5, 'up'))
print(round_to_multiple(23, 5, 'down'))

# Returns:
# 25
# 25
# 20

Here, we modified our function to accept a third argument. We can specify whether we want the function to round to the nearest multiple, round up to a multiple, or round down to a multiple. We accomplish this using if and elif statements. We can see that when we use the keyword argument using any of the ‘nearest’, ‘up’, or ‘down’, the value will round to one of these values.

Rounding a Number to a Multiplier of 10 in Python

While Python doesn’t make it easy to round to any interval, rounding to a multiplier of ten is actually quite straightforward. By a multiplier of ten, we mean increments of 1, 10, 100, 1000, and so on.

You may recall from the earlier section on the Python round() function, that the second argument is the number of decimal places to round to. We can actually pass in a negative value, and the value will round to a multiplier of ten.

Let’s see what happens when we apply a negative argument into the round() function:

# Rounding to a multiplier of ten in Python
number = 145244

rounded_ten = round(number, -1)
rounded_hundred = round(number, -2)
rounded_thousand = round(number, -3)

print(rounded_ten)
print(rounded_hundred)
print(rounded_thousand)

# Returns
# 145240
# 145200
# 145000

Rounding a Pandas Column to a Multiple of a Value

Now that we’ve learned how to round a number to a given multiple of a value, let’s take a look at how we can apply this to a Pandas Dataframe. In many cases, you may want to round an entire dataframe’s column to a specific interval.

Let’s begin by loading a Pandas Dataframe:

# Loading a sample Pandas dataframe
import pandas as pd
df = pd.DataFrame.from_dict({
    'Date': pd.date_range('2022-01-01', '2022-01-05'),
    'Amount': [139, 155, 432, 342, 121]
})

print(df.head())

# Returns:
#         Date  Amount
# 0 2022-01-01     139
# 1 2022-01-02     155
# 2 2022-01-03     432
# 3 2022-01-04     342
# 4 2022-01-05     121

Now that we have our dataframe, we can reuse our earlier function. We can use the Pandas .apply() function to apply our function to the Amount column. Let’s see what this looks like:

# Rounding a Pandas dataframe column to a Multiple
def round_to_multiple(number, multiple):
    return multiple * round(number / multiple)

df['Amount (Rounded)'] = df['Amount'].apply(lambda x: round_to_multiple(x, 5))

print(df.head())

# Returns:
#         Date  Amount  Amount (Rounded)
# 0 2022-01-01     139               140
# 1 2022-01-02     155               155
# 2 2022-01-03     432               430
# 3 2022-01-04     342               340
# 4 2022-01-05     121               120

Here, we have applied the function to our column. This resulted in a new column that had the values rounded to the nearest interval of five.

Conclusion

In this tutorial, you learned how to use Python to round a number to the nearest interval. You learned a recap of the Python round() function and how to use it to round to a multiplier of ten. You then learned how to create a custom function that was able to round a value to its nearest multiple of a given number. You also customized that function to allow the function to either round down to an interval, round up to an interval, or round to the nearest interval. Finally, you learned how to round an entire Pandas dataframe column to an interval of a number.

To learn more about the Python round() function, check out the official documentation here.

Additional Resources

To learn more about related topics, check out the articles below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Leave a Reply

Your email address will not be published. Required fields are marked *