
[英]How to round numbers to the nearest 1000?
我有一些问题要将数字列表向上和向下舍入到最接近的1000。 以下是我的代码: 输出是: 我想将列表四舍五入到最接近的1000.我该怎么做? ...
[英]Round numbers of different lengths to nearest 0 or 5
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
如何将不同长度大小的数字四舍五入到最接近的零或五?
例子:
1291 -> 1290
0.069 -> 0.07
1.08 -> 1.1
14 -> 15
6 -> 5
尝试使用 round() 和 math.ceil() / math.floor() 但由于数字每次的长度都不同,我无法动态调整它,数字从 function 返回,而不是数组。
我写了一个代码并解释了。 它似乎工作。 我没有考虑负数。
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))
动态舍入到最接近的五的有点 pythonic 方法是使用 round() function 和输入数字(除以 5),您希望舍入发生的索引 [-2:百,-1:十,0: whole, 1:1/10ths, 2:1/100s] 并将结果乘以 5。您可以通过使用 decimal 模块查找有多少个小数位来计算此索引。
i = decimal.Decimal('0.069')
i.as_tuple().exponent
-3
注意,这个 function 将数字作为字符串,输出小数位数为负数。
得到这个数字后,将其设为正数,就得到了计算出的索引,可以在开始时放入 function 轮。
round(0.069/5, 3) * 5
您还需要在所有这些计算之前检查数字是否是一个完整数字(意味着没有小数位--17、290、34.0)(在这种情况下您根本不应该使用上面的代码),您可以轻松地通过使用模数,所以整体 function 看起来像这样:
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
希望这有帮助!
在这里,感谢您提供其他解决方案:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.