Search code examples
pythonmathfloor

Python - Flooring floats


This is a really simple question. Lets denote the following:

>>> x = 1.2876

Now, round has this great optional second parameter that will round at that decimal place:

>>> round(x,3)
1.288

I was wondering if there is a simple way to round down the numbers. math.floor(x,3) returns an error rather than 1.287


Solution

  • This is just something that appeared in my mind. Why don't we convert it to string, and then floor it?

    import math
    def floor_float(x, index):
        sx = str(x)
        sx = sx[:index]+str(math.floor(float(sx[index]+"."+sx[index+1])))
        return float(sx)
    

    A little advantage is that it's more representating-error-proof, it's more accurate in representating the numbers (since it's a string):

    >>> floor_float(10.8976540981, 8)
    10.897654
    

    This maybe not the best pythonic solution though.. But it works quite well :)

    Update

    In Python 2.x, math.floor returns a float instead of integer. To make this work you'll to convert the result, to an integer:

        sx = sx[:index]+str(int(math.floor(float(sx[index]+"."+sx[index+1]))))
    

    Update2

    To be honest, the code above is basically nonsense, and too complicated ;)

    Since it's flooring, you can just truncate the string, and float it back:

    def floor_float(x, i):
        return float(str(x)[:i])