[英]Python3: How to round up to a specific number?
I would like to round up to the next 1, 2 or 5 decimal value like in the following code example.我想四舍五入到下一个 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
Eg for values between 0.1 and 0.2 rounded_result should be 0.2, for values between 0.2 and 0.5 rounded_result should be 0.5 and so on.例如,对于 0.1 和 0.2 之间的值 rounded_result 应该是 0.2,对于 0.2 和 0.5 之间的值 rounded_result 应该是 0.5 等等。
Is there a smarter way of doing this?有没有更聪明的方法来做到这一点?
A function like this, maybe?像这样的功能,也许?
It expects thresholds
to be in ascending order.它期望
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))
The output is输出是
0.05 0.1
0.15 0.2
11.3 20.0
74 100.0
116 116
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
This is the vectorized alternative:这是矢量化的替代方案:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.