TL;DR:
round(x)
将其四舍五入并转换为整数。
您没有给任何变量分配round(h)
。当您调用round(h)
时,它会返回整数,但不进行其他操作;您必须更改该行的内容:
h = round(h)
为给h
赋新值,可以采用以下方法。
正如@plowman在评论中所说,Python的round()
函数不像通常期望的那样工作,这是因为变量存储的数字通常不是屏幕上看到的数字。有许多答案解释了这种行为。
避免此问题的一种方法是使用此回答中提到的Decimal。
为了使该答案能够正常工作而不使用额外的库,最好使用自定义的舍入函数。我想出了以下解决方案,根据我的测试,它避免了所有存储问题。它基于使用字符串表示形式,使用repr()
获取(而非str()
!)。它看起来很奇怪,但这是我发现解决所有情况的唯一方法。它适用于Python2和Python3。
def proper_round(num, dec=0):
num = str(num)[:str(num).index('.')+dec+2]
if num[-1]>='5':
return float(num[:-2-(not dec)]+str(int(num[-2-(not dec)])+1))
return float(num[:-1])
测试:
>>> print(proper_round(1.0005,3))
1.001
>>> print(proper_round(2.0005,3))
2.001
>>> print(proper_round(3.0005,3))
3.001
>>> print(proper_round(4.0005,3))
4.001
>>> print(proper_round(5.0005,3))
5.001
>>> print(proper_round(1.005,2))
1.01
>>> print(proper_round(2.005,2))
2.01
>>> print(proper_round(3.005,2))
3.01
>>> print(proper_round(4.005,2))
4.01
>>> print(proper_round(5.005,2))
5.01
>>> print(proper_round(1.05,1))
1.1
>>> print(proper_round(2.05,1))
2.1
>>> print(proper_round(3.05,1))
3.1
>>> print(proper_round(4.05,1))
4.1
>>> print(proper_round(5.05,1))
5.1
>>> print(proper_round(1.5))
2.0
>>> print(proper_round(2.5))
3.0
>>> print(proper_round(3.5))
4.0
>>> print(proper_round(4.5))
5.0
>>> print(proper_round(5.5))
6.0
>>>
>>> print(proper_round(1.000499999999,3))
1.0
>>> print(proper_round(2.000499999999,3))
2.0
>>> print(proper_round(3.000499999999,3))
3.0
>>> print(proper_round(4.000499999999,3))
4.0
>>> print(proper_round(5.000499999999,3))
5.0
>>> print(proper_round(1.00499999999,2))
1.0
>>> print(proper_round(2.00499999999,2))
2.0
>>> print(proper_round(3.00499999999,2))
3.0
>>> print(proper_round(4.00499999999,2))
4.0
>>> print(proper_round(5.00499999999,2))
5.0
>>> print(proper_round(1.0499999999,1))
1.0
>>> print(proper_round(2.0499999999,1))
2.0
>>> print(proper_round(3.0499999999,1))
3.0
>>> print(proper_round(4.0499999999,1))
4.0
>>> print(proper_round(5.0499999999,1))
5.0
>>> print(proper_round(1.499999999))
1.0
>>> print(proper_round(2.499999999))
2.0
>>> print(proper_round(3.499999999))
3.0
>>> print(proper_round(4.499999999))
4.0
>>> print(proper_round(5.499999999))
5.0
最终,经过更正的答案将是:
# Having proper_round defined as previously stated
h = int(proper_round(h))
测试:
>>> proper_round(6.39764125, 2)
6.31
>>> proper_round(6.9764125, 1)
6.1
需要注意的是,第dec
个小数位可能为9,如果第dec+1
个数字>=5,则9将变为0,并且应该向dec-1
个数字进位1。
如果我们考虑到这一点,我们将得到:
def proper_round(num, dec=0):
num = str(num)[:str(num).index('.')+dec+2]
if num[-1]>='5':
a = num[:-2-(not dec)]
b = int(num[-2-(not dec)])+1
return float(a)+b**(-dec+1) if a and b == 10 else float(a+str(b))
return float(num[:-1])
在上述情况中,
b = 10
,之前的版本只会将
a
和
b
连接起来,导致
10
被拼接,末尾的0会消失。这个版本基于
dec
将
b
转换为正确的十进制位数,作为适当的进位。
int(x)
。 - The Brofessor