How to format 1.3435434533e-8 into 1.34e-8 in python? Keep only two digits. The round() method will round this number to zero.
Advertisement
Answer
The “g” formatting suffix on string mini-format language, used both by f-strings, and the .format
method will do that:
JavaScript
x
12
12
1
In [1]: a = 1.34434325435e-8
2
3
In [2]: a
4
Out[2]: 1.34434325435e-08
5
6
In [4]: f"{a:.03g}"
7
Out[4]: '1.34e-08'
8
9
# in contrast with:
10
In [5]: f"{a:.03f}"
11
Out[5]: '0.000'
12