from math import log10 if log10(n) < -5: print "%e" % n else: print "%f" % n
EDIT: it can also be put on one line:
("%e" if log10(n) < -5 else "%f") % n
If n can be negative, use log10(abs(n)) instead of log10(n) .
EDIT 2: Improved based on Adal comments:
"%e" % n if n and log10(abs(n)) < -5 else ("%f" % n).rstrip("0")
This will print 0 as "0". If you want another representation like "0" or "0.0", you will need to make a special case with a separate if .
source share