Python格式百分比

编程入门 行业动态 更新时间:2024-10-10 23:25:39
本文介绍了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格式百分比

本文发布于:2023-07-19 13:37:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1157044.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:百分比   格式   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!