Python3:如何舍入为特定数字?

时间:2020-03-03 06:44:15

标签: python python-3.x

我想四舍五入到下一个1、2或5个十进制值,如以下代码示例所示。

        if result > 0.1:
            if result > 0.2:
                if result > 0.5:
                    if result > 1.0:
                        if result > 2.0:
                            if result > 5.0:
                                if result > 10.0:
                                    if result > 20.0:
                                        if result > 50.0:
                                            rounded_result = 100.0
                                        else:
                                            rounded_result = 50.0
                                    else:
                                        rounded_result = 20.0
                                else:
                                    rounded_result = 10.0
                            else:
                                rounded_result = 5.0
                        else:
                            rounded_result = 2.0
                    else:
                        rounded_result = 1.0
                else:
                    rounded_result = 0.5
            else:
                rounded_result = 0.2
        else:
            rounded_result = 0.1

例如在0.1到0.2之间的值,rounded_result应该是0.2,在0.2到0.5之间的值,rounded_result应该是0.5,依此类推。

是否有更聪明的方法?

3 个答案:

答案 0 :(得分:6)

也许是这样的功能?

它期望thresholds升序。

def round_threshold(value, thresholds):
    for threshold in thresholds:
        if value < threshold:
            return threshold
    return value


thresholds = [0, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]

for test in (0.05, 0.15, 11.3, 74, 116):
    print(test, round_threshold(test, thresholds))

输出为

0.05 0.1
0.15 0.2
11.3 20.0
74 100.0
116 116

答案 1 :(得分:0)

thresholds = [0, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]

for i,thresh in enumerate(thresholds):
    if value<thresh:
        print(thresholds[i])
        break
    if value>thresholds[-1]:
        print(thresholds[-1])
        break

答案 2 :(得分:0)

这是向量化的替代方法:

def custom_round(value, boundaries):
    index = np.argmin(np.abs(boundaries - value)) + 1
    if index < boundaries.shape[0]:
        return boundaries[index]
    else:
        return value

import numpy as np    

boundaries = np.array([0, 0.1, 0.2, 0.5, 
                   1.0, 2.0, 5.0, 10.0, 
                   20.0, 50.0, 100.0])

## test is from @AKX (see other answer)
for test in (0.05, 0.15, 11.3, 74, 116):
   print(test, custom_round(test, boundaries))