askvity

How to round up to nearest number in Python?

Published in Python Math 2 mins read

You can round up to the nearest integer in Python using the math.ceil() function from the math module.

Here's a detailed explanation:

Using math.ceil()

The math.ceil() function always rounds a number up to the nearest integer. To use it, you first need to import the math module.

import math

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

number = 7.0
rounded_up = math.ceil(number)
print(rounded_up)  # Output: 7

number = -2.5
rounded_up = math.ceil(number)
print(rounded_up)  # Output: -2

Explanation

  • import math: This line imports the math module, which contains various mathematical functions.
  • math.ceil(number): This function takes a number as input and returns the smallest integer greater than or equal to that number.

Examples

Here are a few more examples to illustrate how math.ceil() works:

Number math.ceil() Result
2.3 3
5.9 6
-1.7 -1
4 4

Rounding Up to Nearest Multiple

If you need to round up to the nearest multiple of a specific number (e.g., rounding up to the nearest 5 or 10), you can combine math.ceil() with some basic arithmetic:

import math

def round_up_to_multiple(number, multiple):
  """Rounds a number up to the nearest multiple."""
  return multiple * math.ceil(number / multiple)

# Example: Round up to the nearest 5
number = 22
multiple = 5
rounded_up = round_up_to_multiple(number, multiple)
print(rounded_up)  # Output: 25

# Example: Round up to the nearest 10
number = 63
multiple = 10
rounded_up = round_up_to_multiple(number, multiple)
print(rounded_up)  # Output: 70

Summary

The math.ceil() function provides a straightforward way to round any number up to the nearest integer in Python. For rounding up to the nearest multiple of any number, it can be implemented easily with division and multiplication.

Related Articles