Taking the floor of a float

前端 未结 6 422
礼貌的吻别
礼貌的吻别 2021-02-01 13:21

I have found two ways of taking floors in Python:

3.1415 // 1

and

import math
math.floor(3.1415)

The problem

相关标签:
6条回答
  • 2021-02-01 13:46

    Cast it to int if you don't want a float

    int(3.1415 // 1)
    
    0 讨论(0)
  • 2021-02-01 13:51

    Beware that taking the floor and casting to an int are not the same thing with negative numbers. If you really want the floor as an integer, you should cast to an int after calling math.floor().

    >>> int(-0.5)
    0
    >>> math.floor(-0.5)
    -1.0
    >>> int(math.floor(-0.5))
    -1
    
    0 讨论(0)
  • 2021-02-01 13:57

    The second approach is the way to go, but there's a way to shorten it.

    from math import floor
    floor(3.1415)
    
    0 讨论(0)
  • 2021-02-01 14:01

    You can call int() on the float to cast to the lower int (not obviously the floor but more elegant)

    int(3.745)  #3
    

    Alternatively call int on the floor result.

    from math import floor
    
    f1 = 3.1415
    f2 = 3.7415
    
    print floor(f1)       # 3.0
    print int(floor(f1))  # 3
    print int(f1)         # 3
    print int(f2)         # 3 (some people may expect 4 here)
    print int(floor(f2))  # 3
    

    http://docs.python.org/library/functions.html#int

    0 讨论(0)
  • 2021-02-01 14:03
    from math import floor
    
    
    def ff(num, step=0):
        if not step:
            return floor(num)
        if step < 0:
            mplr = 10 ** (step * -1)
            return floor(num / mplr) * mplr
        ncnt = step
        if 1 > step > 0:
            ndec, ncnt = .0101, 1
            while ndec > step:
                ndec *= .1
                ncnt += 1
        mplr = 10 ** ncnt
        return round(floor(num * mplr) / mplr, ncnt)
    

    You can use positive/negative numbers and float points .1, .01, .001...

    0 讨论(0)
  • 2021-02-01 14:09

    As long as your numbers are positive, you can simply convert to an int to round down to the next integer:

    >>> int(3.1415)
    3
    

    For negative integers, this will round up, though.

    0 讨论(0)
提交回复
热议问题