Python格式百分比 [英] Python format percentages

查看:72
本文介绍了Python格式百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use the following snippet for converting a ratio into a percentage:

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

这可以按您期望的那样工作.我想将其扩展为在四舍五入的比率为0或1(但不完全是)的边缘情况下提供更多信息.

This works as you would expect. I want to extend this to be more informative in edge cases, where the rounded ratio is 0 or 1, but not exactly.

是否有一种更Python化的方式(也许使用 format 函数)来做到这一点?或者,我将添加类似于以下内容的子句:

Is there a more pythonic way, perhaps using the format function, to do this? Alternatively I would add a clause similar to:

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

推荐答案

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

I'd recommend running round to figure out if the string formatting is going to round the ratio to 0 or 1. This function also has the option to choose how many decimal places to round to:

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 ,而且可读性不强.

I don't believe there is a shorter way to do it. I also wouldn't recommend using math.isclose, as you'd have to use abs_tol and it wouldn't be as readable.

这篇关于Python格式百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆