Search code examples
pythonstring-formattingexponential

How to force exponential number to be print with leading dot in python?


I am trying to print exponential number in python but I need my number to start by dot. Something like :

>>>print( "{:+???}".format(1.2345678) )
+.1234e+01

Solution

  • If you multiply your number by 10 and format the number with scientific notation, you will have the correct exponent but the coma will be misplaced. Fortunately, you know that there is exactly one character for the sign and exactly one digit before the coma. So you can do

    def format_exponential_with_leading_dot(n):
        a = "{:+e}".format(n * 10)
        return a[0] + '.' + a[1] + a[3:]
    
    
    >>> print format_exponential_with_leading_dot(1.2345678)
    +.1234568e+01