Taking the floor of a float

前端 未结 6 550
礼貌的吻别
礼貌的吻别 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 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

提交回复
热议问题