python - Python 格式百分比
问题描述
我使用以下代码段将比率转换为百分比:
"{:2.1f}%".format(value * 100)
这如你所料。我想扩展它以在边缘情况下提供更多信息,其中舍入比为 0 或 1,但不完全正确。
有没有更pythonic的方式,也许使用format
函数来做到这一点?或者,我会添加一个类似于以下内容的子句:
if math.isclose(value, 0) and value != 0:
return "< 0.1"
解决方案
我建议运行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
它并且它不会那么可读。
推荐阅读
- python - 如何使用 Python 和 Beautiful Soup 从 HTML div 元素访问 href 值?
- jenkins - 从其他应用程序访问 jenkins 构建工件
- c++ - C ++ libcurl返回null?
- c - C语言中的时间转换
- docker-compose - 如何使用引导模式的撰写文件在 Docker 中运行 mysql 路由器
- html - 为什么没有缓存的元标记在网站中不起作用,而 HTML 页面从缓存中加载?
- javascript - 具有动态属性的Vue3重定向
- spring-boot - 如何使用 spring-boot:build-image 嵌入 CA 证书?
- apache-kafka - 如何在 kafka sink 连接器中设置特定表?
- cadence-workflow - 对于循环调用的活动,该活动的重试策略是否适用于每次运行?