How do you round to the nearest multiple in python?
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. Show
In fact, this is possibly something that is easier to do in Excel. Excel provides a function 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
Rounding Numbers in Python: A Quick RecapPython does provide a function that allows you to round a number, the 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 So, say we wanted to round a number to its nearest whole number, we could use the # 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 In the following section, you’ll learn how to develop a custom function that allows you to round to a given multiple in Python. 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:
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 PythonWhile 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 Let’s see what happens when we apply a negative argument into the # 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 ValueNow 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 # 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. ConclusionIn this tutorial, you learned how to use Python to round a number to the nearest interval. You learned a recap of the Python To learn more about the Python Additional ResourcesTo learn more about related topics, check out the articles below:
How do you round to the nearest multiple of 10 in Python?Use the round() function to round a number to the nearest 10, e.g. result = round(num, -1) . When the round() function is called with a second argument of -1 , it rounds to the closest multiple of 10.
How do you round to the nearest multiple of 5?If you need to round a number to the nearest multiple of 5, you can use the MROUND function and supply 5 for number of digits. The value in B6 is 17 and the result is 15 since 15 is the nearest multiple of 5 to 17.
How do you get multiples of 5 in Python?multiples = [n for n in range(1, 101) if n % 5 == 0] print(multiples) Output: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]. from random import choice.. example = choice((1,2,3,4)). print example.. |