Search code examples
pythonmathmissing-features

Rounding a math calculation up, without math.ceil()?


I'm working on a system which doesn't have the math module available. All "Math" functions installed (math.ceil(), math.round(), etc all produce errors).

I have even tried using import math which yields:

<type 'ImportError'>
__import__ not found

Current issue that is stumping me: How can I make a math calculation round up to a whole number without math.ceil?


Solution

  • If x is a float number that you want to round up to an integer, and you want an integer type result, you could use

    rounded_up_x = int(-(-x // 1))
    

    This works because integer division by one rounds down, but using the negative sign before and after doing the division rounds the opposite direction. The int here converts the float result to an integer. Remove that int if you want a floating point value that equals an integer, which is what some programming languages do.

    Hat-tip to @D.LaRocque for pointing out that Python's ceil() function returns an integer type.