首页 > 解决方案 > Python 格式百分比

问题描述

我使用以下代码段将比率转换为百分比:

"{:2.1f}%".format(value * 100)

这如你所料。我想扩展它以在边缘情况下提供更多信息,其中舍入比为 0 或 1,但不完全正确。

有没有更pythonic的方式,也许使用format函数来做到这一点?或者,我会添加一个类似于以下内容的子句:

if math.isclose(value, 0) and value != 0:
    return "< 0.1"

标签: pythonformattingpercentage

解决方案


我建议运行round以确定字符串格式是否会将比率四舍五入为 0 或 1。此函数还可以选择要四舍五入的小数位数:

def get_rounded(value, decimal=1):
    percent = value*100
    almost_one = (round(percent, decimal) == 100) and percent < 100
    almost_zero = (round(percent, decimal) == 0) and percent > 0
    if almost_one:
        return "< 100.0%"
    elif almost_zero:
        return "> 0.0%"
    else:
        return "{:2.{decimal}f}%".format(percent, decimal=decimal)

for val in [0, 0.0001, 0.001, 0.5, 0.999, 0.9999, 1]:
    print(get_rounded(val, 1))

哪个输出:

0.0%
> 0.0%
0.1%
50.0%
99.9%
< 100.0%
100.0%

我不相信有更短的方法可以做到这一点。我也不建议使用math.isclose,因为您必须使用abs_tol它并且它不会那么可读。


推荐阅读