Python round move to the highest number possible, based on days (Full day, Half day)
Full Day = 1, Half Day = 0.5
I want to move to the highest number based on decimal places.
E.g
>>> 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
my code
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)
CodePudding user response:
Try this:-
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)
CodePudding user response:
You can round the value multiplied by 2 and then divide it by 2:
round(x * 2) / 2
Here is how it works:
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
CodePudding user response:
One way is to import math module:
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))