So you can just use format
and specify that you want 20 decimal places but that will be pretty ugly.
>>> format(2.3e-06, ".20f")
'0.00000230000000000000'
But what you can do is use that string and then clean up all of the zeros on the right side using rstrip
>>> format(2.3e-06, ".20f").rstrip("0")
'0.0000023'
>>> format(2.3e-16, ".20f").rstrip("0")
'0.00000000000000023'
Then the only thing left is to figure out if a number is less than 10^-20 and if it is then just print it using the normal exponential formatting that Python will do anyway.
def format_for_up_to_n_decimal_places(num, n_decimal_places):
if num < 10**-n_decimal_places:
return str(num)
else:
return format(num, ".{}f".format(n_decimal_places)).rstrip('0')
Example:
>>> format_for_up_to_n_decimal_places(2.3e-6, 20)
'0.0000023'
>>> format_for_up_to_n_decimal_places(2.3e-50, 20)
'2.3e-50'