我想将数字格式化为百分比,小数点后至少保留 2 位数字;此外,至少有一位有效数字。
例如,我希望 0.123456 看起来像“12.34%”;和 0.00000123456 看起来像“0.0001%”。
有没有简单的方法可以做到这一点?
原因是我的标准输出应该是点后2位小数的定点数;但如果数字小到看起来像 0.00%,我需要至少显示一位有效数字,以便与真正的 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%
具有不同 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%'
关于python - 格式字符串语法 : printing percentage with at least one significant digit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9461065/