Languages
[Edit]
EN

Python - math.ceil() method example

0 points
Created by:
Mark-Rotteveel
537

The math.ceil() function returns an integer value that is greater than or equal to the argument - the result of the round-up operation. 

import math

print(math.ceil(5.0))       # 5

print(math.ceil(2.49))      # 3
print(math.ceil(2.50))      # 3
print(math.ceil(2.51))      # 3

print(math.ceil(-2.49))     # -2
print(math.ceil(-2.50))     # -2
print(math.ceil(-2.51))     # -2

print(math.ceil(0.999))     # 1
print(math.ceil(1.001))     # 2
print(math.ceil(-1.001))    # -1

1. Documentation

Syntax
math.ceil(number)
Parameters

number - float value.

If number is not a float, delegates to x.__ceil__(), which should return an Integral value

Result

Rounded up number value

Descriptionceil() is a method that takes only one parameter and returns a rounded-up value.

2. Rounding with precision up-to n places example

import math


def ceiling_precised(number, precision):
    power = math.pow(10, precision)
    return math.ceil(number * power) / power


print(ceiling_precised(5, 0))     # 5
print(ceiling_precised(5.0, 0))   # 5
print(ceiling_precised(0.5, 0))   # 1

print(ceiling_precised(1.1234, 0))  # 2
print(ceiling_precised(1.1234, 1))  # 1.2
print(ceiling_precised(1.1235, 2))  # 1.13
print(ceiling_precised(1.1235, 3))  # 1.124

print(ceiling_precised(-1.1234, 0))  # -1
print(ceiling_precised(-1.1234, 1))  # -1.1
print(ceiling_precised(-1.1234, 2))  # -1.12
print(ceiling_precised(-1.1234, 3))  # -1.123

print(ceiling_precised(1234, -1))  # 1240
print(ceiling_precised(1234, -2))  # 1300
print(ceiling_precised(1234, -3))  # 2000

print(ceiling_precised(5_000.000_001, 0))   # 5001
print(ceiling_precised(5_000.000_001, 6))   # 5000.000001
print(ceiling_precised(5_000.000_001, -3))  # 6000

References

  1. Floor and ceiling functions - Wikipedia

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - math module

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join