Scientific notation to decimal format in Python

David James Knight
26 Oct 2019

Python uses scientific notation to display very large and very small numbers. This function converts numbers formatted in scientific notation to ordinary decimal strings, with leading whitespace and trailing zeros removed. The default length is up to 10 decimals.

Code

def decimal_str(x: float, decimals: int = 10) -> str:
    return format(x, f".{decimals}f").lstrip().rstrip('0')

Usage examples

x = 1 / 32768

print(x)

>>> 3.0517578125e-05

print(decimal_str(x))

>>> '0.0000305176'

Passing optional argument for decimal length:

print(decimal_str(x, 15))

>>> '0.000030517578125'