Python Format Float (Decimal Points) Value or None

August 17, 2019
v1 = 0.00000028
v2 = None

print(f"v1={v1}, v2={v2}")
# v1=2.8e-07, v2=None

To print with decimal points without exponential notation

print(f"v1={v1:.8f}, v2={v2}")
# v1=0.00000028, v2=None

Sadly, TypeError: unsupported format string passed to NoneType.__format__ is raised when the value is None

print(f"v1={v1:.8f}, v2={v2:.8f}")

To handle formating of float value which could be None as well.

def f(v):
    if v is None:
        return v
    return f"{v:.08f}"

print(f"v1={f(v1)}, v2={f(v2)}")
# v1=0.00000028, v2=None

NOTE: Format float without trailing zeros.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.