floor and ceil with number of decimals

前端 未结 3 1627
情话喂你
情话喂你 2021-01-05 06:51

I need to floor a float number with an specific number of decimals.

So:

2.1235 with 2 decimals --> 2.12
2.1276 with 2 decimals --> 2.12  (round         


        
3条回答
  •  猫巷女王i
    2021-01-05 07:37

    Neither Python built-in nor numpy's version of ceil/floor support precision.

    One hint though is to reuse round instead of multyplication + division (should be much faster):

    def my_ceil(a, precision=0):
        return np.round(a + 0.5 * 10**(-precision), precision)
    
    def my_floor(a, precision=0):
        return np.round(a - 0.5 * 10**(-precision), precision)
    

提交回复
热议问题