python - 格式字符串语法 : printing percentage with at least one significant digit

标签 python formatting python-3.x

我想将数字格式化为百分比,小数点后至少保留 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/

相关文章:

python - 编写一个函数,反向返回一个data.txt

r - 在数据帧上使用 gsub()

python - 帮助生成器函数中的逻辑

python - 图像中存储的像素值会自动更改。如果图像再次在另一个函数中打开

php - 将简单的php代码转换为python

c - 使用用户输入填充结构并通过指针访问

java - Eclipse 或 SQL Developer 可以自动取消引用 Java 字符串吗?

python - 如何创建一个在每次设置事件时运行函数的事件?

python - Django 验证 m2m 模型字段

Python 将列表 reshape 为多维列表