简体   繁体   中英

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

I'm trying to print numbers that range across 8 orders of magnitude. I would like to print them with a fixed number of sig figs but not in scientific notation.

Toy program:

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

Desired output of this program:

120000
12000
1200
120
12
1.2
0.12
0.012

I've found a couple solutions that aren't quite right.

Option 1) f'{n:.2f'} gives output:

123456.00
12345.60
1234.56
123.46
12.35
1.23
0.12
0.01

It's not in scientific notation, but number of sig figs is all wrong.

Option 2) f'{n:.2'} gives output:

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

Sig figs are correct, but large numbers get printed in scientific notation, rather than padding zeros. My numbers aren't big enough for scientific notation, so readability suffers. I could hack a method to do this, but I'm hoping there's a magic format string to do this for me. Thanks

The simplest solution is first pip installing sigfig . Then you can use this code:

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

I did end up writing a method for this, for anyone for whom sigfig is unavailable

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM