[英]Python function to round to the nearest .5
在 python 中,如何將數字四舍五入到最接近的 0.5。
例如
100.4 將四舍五入為 100.5
100.6 將四舍五入為 100.5
100.9 將四舍五入為 101
Python 的內置round
function 可用於將數字四舍五入到一定的小數位數。 通過將數字乘以 2,將其四舍五入到沒有小數位並再次除以,我們可以將一個數字四舍五入到最接近的 0.5:
num = 3.46
result = round(num * 2) / 2
print(result) # 3.5
作為 function 這是:
def to_nearest_half(num):
return round(num * 2) / 2
function 也可以推廣到任何十進制:
def to_nearest(num, decimal):
return round(num / decimal) * decimal
那將是
def roundhalf(x: float):
return round(x*2)/2
可以用
for x in [100.4, 100.6, 100.9]:
print(roundup(x))
output 確實是
100.5
100.5
101.0
執行此操作的傳統方法是乘以允許小數舍入目標為整數的因子,進行舍入,然后將該因子除以。 在這種情況下,因子是 2,因為 0.5 乘以 2 是 1,一個整數。
x = 100.4
y = round(x * 2) / 2
要始終使用一個小數位打印它,您可以使用str.format()
。
'{:.1f}'.format(round(x * 2) / 2)
最簡單的方法是:
def myRound(x):
if 0 <= (x % int(x)) <= 0.25 or 0.75 <= (x % int(x)) <= 0.99:
return round(x)
else:
return int(x) + 0.5
解釋:
我假設您希望將低於 25 的任何值舍入為 0,將高於 75 的任何值舍入為 1,並將介於兩者之間的所有值舍入為 5。您可以修改邊界。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.