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