0
0
PythonHow-ToBeginner · 3 min read

How to Use math.ceil() and math.floor() in Python

In Python, use math.ceil() to round a number up to the nearest integer and math.floor() to round down to the nearest integer. Both functions require importing the math module before use.
📐

Syntax

The math.ceil(x) function returns the smallest integer greater than or equal to x. The math.floor(x) function returns the largest integer less than or equal to x.

Both functions take a single numeric argument x and return an integer.

python
import math

# Round up
math.ceil(x)

# Round down
math.floor(x)
💻

Example

This example shows how to use math.ceil() and math.floor() to round the number 3.7 up and down.

python
import math

number = 3.7
rounded_up = math.ceil(number)
rounded_down = math.floor(number)

print(f"Original number: {number}")
print(f"Rounded up (ceil): {rounded_up}")
print(f"Rounded down (floor): {rounded_down}")
Output
Original number: 3.7 Rounded up (ceil): 4 Rounded down (floor): 3
⚠️

Common Pitfalls

A common mistake is forgetting to import the math module before using ceil or floor. Another is confusing ceil and floor functions, which do opposite rounding.

Also, these functions always return integers, so if you expect a float, you need to convert it back.

python
import math

# Wrong: forgetting import
# rounded = ceil(3.7)  # NameError: name 'ceil' is not defined

# Correct usage
rounded_up = math.ceil(3.7)
rounded_down = math.floor(3.7)

print(rounded_up, rounded_down)
Output
4 3
📊

Quick Reference

FunctionDescriptionExampleResult
math.ceil(x)Rounds x up to nearest integermath.ceil(2.3)3
math.floor(x)Rounds x down to nearest integermath.floor(2.7)2

Key Takeaways

Import the math module before using math.ceil() or math.floor().
Use math.ceil() to round numbers up to the nearest integer.
Use math.floor() to round numbers down to the nearest integer.
Both functions return integers, not floats.
Remember ceil and floor do opposite rounding directions.