I want to format a number as a percent, with at least 2 digits after the decimal point; and in addition, with at least one significant digit.
For example, I want 0.123456 to look like '12.34%'; and 0.00000123456 to look like '0.0001%'.
Is there a simple way to achieve that?
The reason is that my standard output should be a fixed point number with 2 decimals after the point; but if the number is so small that it looks like 0.00%, I need to show at least one significant digit so it can be distinguished from true 0.
import math
def format_percent(x, at_least=2):
return '{1:.{0}%}'.format(max(at_least, int(-math.log10(x))-1), x)
for x in (1., .1, .123456, .0123, .00123, .000123, .0000123, .00000123):
print x, format_percent(x, 2)
1.0 100.00%
0.1 10.00%
0.123456 12.35%
0.0123 1.23%
0.00123 0.12%
0.000123 0.01%
1.23e-05 0.001%
1.23e-06 0.0001%
More cases with different at_least:
>>> format_percent(.1, 3)
'10.000%'
>>> format_percent(.012345678, 5)
'1.23457%'
>>> format_percent(.000123, 0)
'0.01%'
>>> format_percent(1.23456, 0)
'123%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With