pythonnotationexponent

How to write a number in scientific notation in Python keeping the mantissa as integer


Suppose I have x=3.141516 and y=0.00129. I need to format those numbers in scientific notation but the mantissa must not have decimal places. For example:

x = 3141516e-6
y = 129e-5

I have no idea how to solve this, since formatting in Python looks always assume decimal places.


Solution

  • I'm not aware how you can do it with str.format (to not have any decimal places), but you can construct the string manually (with help of decimal module):

    import decimal
    
    
    def get_num(x):
        t = decimal.Decimal(str(x)).as_tuple()
        return f'{"-" if t.sign else ""}{"".join(map(str, t.digits))}e{t.exponent}'
    
    
    print(get_num(3.141516))
    print(get_num(0.00129))
    print(get_num(-1.23))
    

    Prints:

    3141516e-6
    129e-5
    -123e-2