After looking around, Gao Zan replied , Nobody even mentioned this .
Everybody knows ,round() It is used for rounding .
however , There are special circumstances :
Have you found any problems ?
7.55 Keep one decimal place , Rounding , Should have 7.6, But I got 7.5
1.315 Keep two decimal places , Rounding , Should the 1.32, But I got 1.31
because ,Python It does not follow rounding , It is “ Round to the nearest pair ”
Python Official documents :
round Introduce : Built in functions — Python 3.10.5 file
The controversy and limitation of floating point arithmetic :15. Floating point arithmetic : Disputes and restrictions - Python 3.10.5 file
So , I wrote a special function , Fix this problem ( If it counts as a problem ):
def new_round(v_value, ndigits=1):
"""
Repair python The question of rounding
:param ndigits: Keep a few decimal places
:param v_value: Enter the value
:return: Output value
"""
f = int(v_value) % 10
if f <= 4:
v_value = (int(v_value) // 10) / 10
else:
v_value = (int(v_value) // 10 + 1) / 10
print(v_value)
return v_value
Whether it counts or not Python Of bug, But you must know this .
Don't let your program , Because of it , Calculate the wrong result , He didn't know it !
By then , If not python Of bug, It's also your program bug 了 !!
Python Is there any unknown pit ? - You know | Horse brother python say
I'm brother ma , The whole network has tens of thousands of fans , Welcome to share python technology .
Search by platform “ Horse brother python say ”: You know 、 Bili, Bili 、 The little red book 、 Sina weibo .