How to Round a Number Up in Python?

3/5 - (1 vote)

Problem Formulation: Given a float number. How to round the float up in Python?

Here are some examples of what you want to accomplish:

  • 42.42 --> 43
  • 21.00001 --> 22
  • -0.1 --> 0

Solution: If you have little time, here’s the most straightforward answer:

To round a number up in Python, import the math library with import math, and call math.ceil(number) that returns the ceiling of number, i.e., the smallest integer greater than or equal to number.

In general, there are at least four ways to round a float number x up in Python:

  • Round up: The math.ceil(x) function rounds number x up to the next full integer.
  • Round up (float representation): Alternatively, numpy.ceil(x) rounds up and returns a float representation of the next full integer (e.g., 2.0 instead of 2).
  • Round down: The math.floor(x) function rounds number x down to the next full integer.
  • Round up and down: The Python built-in round(x) function rounds x up and down to the closest full integer.
  • Vanilla Python: The one-liner expression int(x) + ((int(x)!=x) if x>0 else 0) rounds x up without external dependency. An alternative is the expression int(x) + bool(x%1) to round up positive numbers.

Let’s dive into each of those and more options in the remaining article. I guarantee you’ll get out of it having learned at least a few new Python tricks in the process!

Method 1: math.ceil()

To round a number up in Python, import the math library with import math, and call math.ceil(number).

The function returns the ceiling of the specified number that is defined as the smallest integer greater than or equal to number

The following code shows how to round the number 42.42 up to 43, 21.00001 to 22, and -0.1 to 0 using the math.ceil() function.

import math


print(math.ceil(42.42))
# 43

print(math.ceil(21.00001))
# 22

print(math.ceil(-0.1))
# 0

The following video shows the math.ceil() as well as the math.floor() functions — feel free to watch it to gain a deeper understanding:

Python Math floor(), ceil(), trunc(), and modf()

Method 2: np.ceil()

To round a number up in Python, import the NumPy library with import numpy as np, and call np.ceil(number).

The function returns the ceiling of the specified number that is defined as the smallest integer greater than or equal to number.

The following code shows how to round the number 42.42 up to 43, 21.00001 to 22, and -0.1 to 0 using the np.ceil() function.

import numpy as np


print(np.ceil(42.42))
# 43.0

print(np.ceil(21.00001))
# 22.0

print(np.ceil(-0.1))
# 0.0

Both math.ceil() and np.ceil() round up to the next full integer. The difference between math.ceil() and np.ceil() is that the former returns an integer and the latter returns a float value.

Method 3: int(x) + bool(x%1)

You can also use the following vanilla Python snippet to round a number x up to the next full integer:

  • If x is negative, round up by calling int(x).
  • If x is positive, round up by calling int(x) + bool(x%1).

Explanation: Any non-zero expression passed into the bool() function will yield True which is represented by integer 1. The modulo expression x%1 returns the decimal part of x. If it is non-zero, we add bool(x%1) == 1, i.e., we round up. If it is zero, we add bool(x%1) == 0, i.e., we’re already done.

Here’s what this looks like in a simple Python function:

def round_up(x):
    if x<0:
        return int(x)
    return int(x) + bool(x%1)


print(round_up(42.42))
# 43

print(round_up(21.00001))
# 22

print(round_up(-0.1))
# 0

You can watch my explainer video on modulo here:

Python Modulo - A Simple Illustrated Guide

Method 4: int(x) + int(x)!=x

If you don’t want to import the math module, you can use the one-liner beauty:

int(x) + ((int(x)!=x) if x>0 else 0)

This ternary expression rounds up number x to the next full integer. This first cuts off the decimal part using the int() function and then adds one if there is a non-zero decimal part (and it’s a positive number) and zero otherwise.

If the number x is negative, the expression int(x) already rounds up to the next full integer.

def round_up(x):
    return int(x) + ((int(x)!=x) if x>0 else 0)


print(round_up(42.42))
# 43

print(round_up(21.00001))
# 22

print(round_up(-0.1))
# 0
  • The int() built-in function cuts of the decimal part, i.e., rounds down.
  • The expression int(x)!=x evaluates to 1 if the decimal part of x is greater than 0. Otherwise, it becomes 0.
  • This helps us because only if the decimal part is greater than 0, we need to add +1 to the rounded-down number to round it up.
  • If the number x is negative, the expression int(x) already rounds up to the next full integer, so we use the ternary operator (...) if (...) else (...) to account for this condition.

You can watch my introductory video on the ternary operator here:

The Python Ternary Operator – And a Surprising One-Liner Hack

Method 5: round()

This method is probably not exactly what you want because it rounds a number up and down, depending on whether the number is closer to the smaller or larger next full integer. However, I’ll still mention it for comprehensibility.


Python’s built-in round() function takes two input arguments:

  • a number and
  • an optional precision in decimal digits.

It rounds the number to the given precision and returns the result. The return value has the same type as the input number—or integer if the precision argument is omitted.

Per default, the precision is set to 0 digits, so round(3.14) results in 3.

Here are three examples using the round() function—that show that it doesn’t exactly solve our problem.

import math


print(round(42.42))
# 42

print(round(21.00001))
# 21

print(round(-0.1))
# 0

Again, we have a video on the round() function — feel free to watch for maximum learning!

Python round() — A Helpful Interactive Guide

Method 6: Rounding Up After Integer Division

If the float to be rounded up comes from a division operation a/b, you can also use integer division a//b to round down to the next integer, and increment this by one. Thus, the expression a//b+1 rounds the resulting number up if a is not divisible by b, otherwise, the result of a//b would already provide the “rounded-up” semantics.

You can create a simple ternary operator x if y else z to differentiate between those two conditions:

a = int(input('a='))
b = int(input('b='))

rounded_up = a//b + 1 if a%b else a//b
print(rounded_up)

The code goes through the following steps:

  • Get the input strings from the user using the built-in input() function.
  • Convert the inputs to integer values using the built-in int() function.
  • Use the modulo operation a%b to differentiate between b being a divisor of a or not.
  • If not, the result will have a remainder and you can use integer division a//b to round down and increment this by one.
  • If yes, the result won’t have a remainder and you can simply use integer division because it, mathematically, would already be considered to be rounded up.
  • You use the ternary operator to pack this logic into a single line of code.

Here’s an example execution that was rounded up:

a=8
b=3
3

And here’s an example execution that wasn’t:

a=8
b=4
2

An alternative one-liner to round up two integers would be the following beauty:

a = int(input('a='))
b = int(input('b='))

rounded_up = a // b + (a % b > 0)
print(rounded_up)

The expression (a % b > 0) evaluates to True if b is not a divisor of a, otherwise it evaluates to False. As the Boolean True is represented by the integer value 1 in Python and Boolean False by the integer value 0 in Python, the expression increments only if b is not a divisor of a.

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!