Python – SIMPLE Floor and Ceiling Functions that WORK

Python – SIMPLE Floor and Ceiling Functions that WORK
June 27, 2017 Reece

Python Logo

Floor and Ceiling functions… not native in Python?

First off, let me preface that I love Python. Despite random quirks like this, it is so extremely versatile. It can be used make a LED blink on a RaspberryPi to doing intense data analysis projects, building websites, helping power Instagram and a lot in between. With that out of the way, let’s look at one of those quirks and how to remedy it.

I was working on a project where I needed a Floor and a Ceiling function with different degrees of precision. I was surprised when I couldn’t find this natively in the Math module in Python.
(That or I wasn’t looking hard enough.)

After some digging around on StackOverflow I was able to cobble together a solution that works. Though they work slightly differently in terms of precision, they do work. I could have put more time into it (and probably will later) to make them work the same, but I was up against a deadline.

Code for the functions below:

def ceil(x, p):
    '''
    x = number to apply function to
    p = level of precision
    '''
    return p * math.ceil(float(x)/p)

def floor(x, p):
    '''
    x = number to apply function to
    p = level of precision
    '''
    factor = 10.0 ** p
    return math.floor(x * factor) / factor

I found a lot of answers for this but the hard part was finding ones that worked. Hopefully, this simple solution works for you and you can stop searching for it and move on with your project.



Full example code below:

import math

def ceil(x, p):
    return p * math.ceil(float(x)/p)

def floor(x, p):
    factor = 10.0 ** p
    return math.floor(x * factor) / factor

testVal = 32.62586

print(ceil(testVal,1))
# 33

print(ceil(testVal,0.1))
# 32.7

print(ceil(testVal,0.001))
# 32.626

print(floor(testVal,1))
# 32.6

print(floor(testVal,2))
# 32.62

print(floor(testVal,3))
# 32.625

print(floor(testVal,0))
# 32.0

Questions?

Comment below or contact me.

0 Comments

Leave a reply

Your email address will not be published. Required fields are marked *

*