Python Format Percentages
I use the following snippet for converting a ratio into a percentage: '{:2.1f}%'.format(value * 100) This works as you would expect. I want to extend this to be more informative in
Solution 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) andpercent<100
almost_zero = (round(percent, decimal) ==0) andpercent>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))
Which outputs:
0.0%
> 0.0%
0.1%
50.0%
99.9%
< 100.0%
100.0%
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.
Solution 2:
Assuming Python 3.6+, marking exactly zero or exactly 100% could be done with:
>>> for value in (0.0,0.0001,.9999,1.0):
... f"{value:6.1%}{'*'if value == 0.0or value == 1.0else' '}"
...
' 0.0%*'' 0.0% ''100.0% ''100.0%*'
Post a Comment for "Python Format Percentages"