基于天數(全天、半天),Python 回合移動到盡可能高的數字
全天 = 1,半天 = 0.5
我想移動到基于小數位的最高數字。
例如
>>> round(30/12, 2)
2.5 # 2 and half day
>>> round(20/12, 2)
1.67 # 2 Days
>>> round(15/12, 2)
1.25 # 1 Day
>>> round(4/12, 2)
0.33 # Half day
我的代碼
total_leaves = 15 # 30,10,20,15
monthly_leaves = round(total_leaves / 12, 2)
monthly_leaves_final = 0
leave_one = int(str(monthly_leaves).split('.')[0])
leave_two = Decimal(str(monthly_leaves).split('.')[1])
if leave_two in [5, 5.0]:
monthly_leaves_final = '%s.%s' % (leave_one, 5)
if leave_two > 5:
monthly_leaves_final = '%s.%s' % (leave_one 1, 0)
if leave_two < 5:
monthly_leaves_final = '%s.%s' % (leave_one - 1, 0)
uj5u.com熱心網友回復:
嘗試這個:-
total_leaves = 15 # 30,10,20,15
monthly_leaves = round(total_leaves / 12, 2)
monthly_leaves_final = 0
leave_one,leave_two = str(monthly_leaves).split('.')
leave_one = int(leave_one)
leave_two= int(leave_two '0') if len(leave_two)==1 else int(leave_two)
if leave_two == 50:
monthly_leaves_final = '%s.%s' % (leave_one, 5)
elif leave_two > 50:
monthly_leaves_final = '%s.%s' % (leave_one 1, 0)
elif leave_two < 50:
monthly_leaves_final = '%s.%s' % (leave_one, 0)
print(monthly_leaves_final)
uj5u.com熱心網友回復:
您可以將乘以 2 的值四舍五入,然后再除以 2:
round(x * 2) / 2
下面是它的作業原理:
lst = [round(i / 6, 3) for i in range(10)]
for el in lst:
print(el, '\t->', round(el * 2) / 2)
# Output:
# 0.0 -> 0.0
# 0.167 -> 0.0
# 0.333 -> 0.5
# 0.5 -> 0.5
# 0.667 -> 0.5
# 0.833 -> 1.0
# 1.0 -> 1.0
# 1.167 -> 1.0
# 1.333 -> 1.5
# 1.5 -> 1.5
uj5u.com熱心網友回復:
一種方法是匯入數學模塊:
monthly_leaves = round(total_leaves/12, 2)
monthly_leaves_final = 0
decimal = str(float(monthly_leaves)).split('.')[1]
if int(decimal) == 5:
monthly_leaves_final = (monthly_leaves)
elif int(decimal) > 50:
monthly_leaves_final = (math.ceil(monthly_leaves))
elif int(decimal) < 50:
monthly_leaves_final = (math.floor(monthly_leaves))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/353554.html
