pythonceil

Python round to next highest power of 10


How would I manage to perform math.ceil such that a number is assigned to the next highest power of 10?

# 0.04  ->  0.1
# 0.7   ->  1
# 1.1   ->  10  
# 90    ->  100  
# ...

My current solution is a dictionary that checks the range of the input number, but it's hardcoded and I would prefer a one-liner solution. Maybe I am missing a simple mathematical trick or a corresponding numpy function here?


Solution

  • You can use math.ceil with math.log10 to do this:

    >>> 10 ** math.ceil(math.log10(0.04))
    0.1
    >>> 10 ** math.ceil(math.log10(0.7))
    1
    >>> 10 ** math.ceil(math.log10(1.1))
    10
    >>> 10 ** math.ceil(math.log10(90))
    100
    

    log10(n) gives you the solution x that satisfies 10 ** x == n, so if you round up x it gives you the exponent for the next highest power of 10.

    Note that for a value n where x is already an integer, the "next highest power of 10" will be n:

    >>> 10 ** math.ceil(math.log10(0.1))
    0.1
    >>> 10 ** math.ceil(math.log10(1))
    1
    >>> 10 ** math.ceil(math.log10(10))
    10