简体   繁体   English

基于天数(全天、半天),Python 回合移动到可能的最高数字

[英]Python round move to highest number possible, based on days (Full day, Half day)

Python round move to the highest number possible, based on days (Full day, Half day)基于天数(全天、半天),Python 回合移动到尽可能高的数字

Full Day = 1, Half Day = 0.5全天 = 1,半天 = 0.5

I want to move to the highest number based on decimal places.我想移动到基于小数位的最高数字。

Eg例如

>>> 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)

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)

You can round the value multiplied by 2 and then divide it by 2:您可以将乘以 2 的值四舍五入,然后再除以 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

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM