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:
In [1]: a = 1.34434325435e-8
In [2]: a
Out[2]: 1.34434325435e-08
In [4]: f"{a:.03g}"
Out[4]: '1.34e-08'
# in contrast with:
In [5]: f"{a:.03f}"
Out[5]: '0.000'