如何在控制 Python 中的有效数字的同时抑制科学记数法?

How do I suppress scientific notation while controlling significant figures in Python?

我正在尝试打印 8 个数量级范围内的数字。我想用固定数量的 sig figs 打印它们,但不是科学记数法。

玩具节目:

n = 123456.0
while n > 0.01:
    print(<format statement>)
    n = n/10

此程序的期望输出

120000
12000
1200
120
12
1.2
0.12
0.012

我发现了一些不太正确的解决方案。

选项 1) f'{n:.2f'} 给出输出:

123456.00
12345.60
1234.56
123.46
12.35
1.23
0.12
0.01

不是科学计数法,但是数字都是错的

选项 2) f'{n:.2'} 给出输出:

1.2e+05
1.2e+04
1.2e+03
1.2e+02
1.2e+01
1.2
0.12
0.012

Sig figs 是正确的,但大数字以科学计数法打印,而不是填充零。我的数字不够大,无法进行科学计数,因此可读性受到影响。我可以破解一种方法来执行此操作,但我希望有一个神奇的格式字符串可以为我执行此操作。谢谢

最简单的解决方案是先 pip 安装 sigfig。 然后你可以使用这个代码:

from sigfig import round
n = 123456.0
while n > 0.01:
    # rounds to two significant figures
    print(round(n, sigfigs=2))
    n = n/10

我确实为此编写了一个方法,供 sigfig 不可用的任何人使用

def num_fmt(n: float, sf: int = 3) -> str:
    """
    Returns number as a formatted string with specified number of significant figures
    :param n: number to format
    :param sf: number of sig figs in output
    """
    r = f'{n:.{sf}}'  # use existing formatter to get to right number of sig figs
    if 'e' in r:
        # for big numbers, strip scientific notation and pad with zeros
        exp = int(r[-2:])
        r = r[0]+r[2:-4] + '0' * (exp-sf+2)
    return r