'How to format very small numbers in python?

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.



Solution 1:[1]

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'

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jsbueno
Solution 2 LukasNeugebauer