首页 > 解决方案 > 将加载条的百分比四舍五入,但将 [99-100) 调整为 99%,将 (0, 1] 调整为 1%

问题描述

我有一个介于 0 和 1(含)之间的浮点数,我以百分比形式打印:

complete = 999
total = 1000

print(f"Completed {complete} out of {total} ({complete / total:.0%})")

但是当我真正接近(但不是完全达到)100% 时,它会跳枪并打印 100%,这不是用户对加载屏幕的期望:

Completed 999 out of 1000 (100%)

我想上面说的是 99%,即使它确实达到了 100%。同样,如果我完成了 1/1000,我想说我完成了 1% 而不是什么都没有(0%)。

标签: pythonnumber-formatting

解决方案


这是一种方法:

complete = 999 
total = 1000

pct = math.floor(complete * 100.0/total)/100
if complete / total >= 0.001:
    pct = max(pct, 0.01)
    
print(f"Completed {complete} out of {total} ({pct:.0%})")

输出:

Completed 999 out of 1000 (99%)

如果complete是 1,即使它更接近 0,它也会打印 1%。

更完整的解决方案

遵循相同理性的更全面的解决方案将四舍五入到 50% 的所有内容,然后从 50 到 100% 的所有内容向下舍入:

def get_pct(complete, total):
    
    pct = (complete * 100.0 / total)
    if pct > 50: 
        pct = math.floor(pct) /100
    else:
        pct = math.ceil(pct) /100
    return pct

complete = 1
total = 1000
print(f"Completed {complete} out of {total} ({get_pct(complete, total):.0%})")
#==> Completed 1 out of 1000 (1%)

complete = 999
total = 1000
print(f"Completed {complete} out of {total} ({get_pct(complete, total):.0%})")
#==> Completed 999 out of 1000 (99%)

complete = 555
total = 1000
print(f"Completed {complete} out of {total} ({get_pct(complete, total):.0%})")
#==> Completed 555 out of 1000 (55%)

complete = 333
total = 1000
print(f"Completed {complete} out of {total} ({get_pct(complete, total):.0%})")
#==> Completed 333 out of 1000 (34%)

推荐阅读