How to format very small numbers in python?

Viewed 165

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.

2 Answers

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'

You could do something like round(number, 10), which leaves you with 10 digits after the decimal point. Since you shift the point by 8 (^-8), this leaves you with two printed decimal places.

Related