最接近0或5的不同长度的整数



如何将不同长度大小的数字四舍五入到最接近的0或5 ?

的例子:

1291 -> 1290
0.069 -> 0.07
1.08 -> 1.1
14 -> 15
6 -> 5

尝试使用round()和math.ceil()/math.floor(),但由于数字每次长度不同,我不能动态地适应它,数字从函数而不是数组返回。

给你,谢谢你的其他解决方案:

import math
import decimal
def round_half_up(n):
if (str(n).find(".") > 0):
decimalsource = len(str(n).split(".")[1])
base = 10**decimalsource
number = n*base
rounded = 5 * round(number/5)
result = rounded / base
if (result == int(result)):
return int(result)
else:
return result
else:
return 5 * round(n/5)

print(round_half_up(1291))
print(round_half_up(0.069))
print(round_half_up(1.08))
print(round_half_up(14))
print(round_half_up(6))
print(round_half_up(12.121213))
print(round_half_up(12.3))
print(round_half_up(18.))
print(round_half_up(18))

我写了一个代码并解释了。它似乎起作用了。我没有考虑到负数。

import numpy as np
convDict = {
"0":"0",
"1":"0",
"2":"0",
"3":"5",
"4":"5",
"5":"5",
"6":"5",
"7":"5",
"8":"0",
"9":"0"
}
def conv(f):
str_f = str(f)

# if input is like, 12. or 13.0,so actually int but float data type
# We will get rid of the .0 part
if str_f.endswith(".0"):
str_f = str(int(f))
# We need last character, and other body part
last_f = str_f[-1]
body_f = str_f[:-1]
# if last char is 8 or 9 we should increment body last value
if last_f in "89":
# Number of decimals
numsOfDec = body_f[::-1].find('.')
# numsOfDec = -1 means body is integer, we will add 1
if numsOfDec == -1:
body_f = str(int(body_f) + 1)
else:
# We will add 10 ** -numsOfDec , but it can lead some numerical differences like 0.69999, so i rounded
body_f = str(np.round(float(body_f) + 10 ** (-numsOfDec),numsOfDec))
# Finally we round last char
last_f = convDict[last_f]
return float(body_f + last_f)

还有一些例子,

print(conv(1291))
print(conv(0.069))
print(conv(1.08))
print(conv(14))
print(conv(6))
print(conv(12.121213))
print(conv(12.3))
print(conv(18.))
print(conv(18))

动态舍入到最接近5的python方法是使用round()函数和输入数字(除以5),您希望舍入的索引[-2:百位,-1:十位,0:整位,1:1/10ths, 2:1/100]并将结果乘以5。您可以通过使用decimal模块查找有多少位小数来计算该索引。

i = decimal.Decimal('0.069')
i.as_tuple().exponent
-3 

注意,这个函数接受数字作为字符串并输出数字

在得到这个数字之后,使它为正,这样你就有了计算出来的索引,可以在开始的round函数中输入。

round(0.069/5, 3) * 5

您还需要在所有这些计算之前检查数字是否为整数(意味着没有小数—17,29,34.0)(在这种情况下,您根本不应该使用上面的代码),您可以通过使用模数轻松完成,因此整个函数看起来像这样:

if number % 1 == 0:
return round(int(number)/5)*5
else:
index = decimal.Decimal(str(number)).as_tuple().exponent
return round(number/5, -index)*5

希望有帮助!

最新更新