AppDividend
Latest Code Tutorials

Python floor() and ceil() Function: The Complete Guide

Python’s math.floor() method rounds a number down to the nearest integer, if necessary, and returns the output. It is one of the Mathematical functions available in the Python math library. 

Likewise, the math.ceil() method in Python returns the ceiling value of the input value. Let’s see these functions in detail with their syntax, parameters, and example.

Python floor

Python floor() is a built-in function that returns the floor of input numeric value. It takes a numeric number as an argument and returns the largest integer not greater than the input value.

The math.floor() function returns the nearest integer value, which is less than or equal to a specified expression or value.

To work with the floor() method, you need to import the math module from Python.

Syntax

See the following syntax of the math.floor() method.

import math

math.floor(x)

Arguments

The math.floor() method takes x as a numeric number, which is a required parameter.

Example

Let’s see the following code that demonstrates the Python floor method.

# app.py

import math

caltech = math.floor(300.72)
print(caltech)

First, We imported the math library using the import statement. It will allow us to use mathematical functions like the floor.

In the next line, we applied the math.floor() function and passed the argument 300.72, and it will give us the output, and we have stored that output inside the Caltech variable and then display it in the Python console.

See the output.

Python Floor and Ceil Function Tutorial

See the other following examples.

# app.py

import math

print("math.floor(-19.21): ", math.floor(-19.21))
print("math.floor(19.46): ", math.floor(19.46))
print("math.floor(46.19): ", math.floor(46.19))

An output of the above code is below.

Floor and Ceil Function

Python ceil

Python ceil() is a built-in method that returns the ceiling value of the input value, which is the smallest integer not less than the input value. The ceil() method takes only one input value, the numeric value.

Syntax

import math

math.ceil(x)

Arguments

The math.ceil() function takes x as an input numeric value.

Example

To work with the ceil() method, you need to import the math module from Python.

See the following coding example.

# app.py

import math

caltech = math.ceil(300.72)
print(caltech)

See the output.

Python math.ceil() Function

See the other following examples.

# app.py

import math

print("math.ceil(-19.63): ", math.ceil(-19.63))
print("math.ceil(19.63): ", math.ceil(19.63))
print("math.ceil(46.63): ", math.ceil(46.63))

The output of the above code is the following.

Ceil Function Tutorial With Example

That is it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.