pythonscientific-notationformat-specifiersmantissa

How to convert a E notation string to a float with fixed exponent in python


My instrumentation device returns strings of data such as 2.89E-6, 9.87E-1, 4.18E-4 etc.

How can I change the representation such that the exponent is always -3. My intention is to manually extract the Mantissa of the resultant expression.

Desired output:

string 2.89E-6 becomes-> float 0.00289E-3

string 9.87E-1 becomes-> float 987E-3

string 4.18E-4 becomes-> float 0.418E-3

Eventually, would like to extract the mantissa-> 0.000289, 987, 0.418 respectively as my “final” output.


Solution

  • You can use the decimal module for manipulation of decimal numbers, then convert to float at the end if needed.

    import decimal
    
    data = ['2.89E-6', '9.87E-1', '4.18E-4']
    
    for s in data:
        n = decimal.Decimal(s)
        print(float(n * 1000))
    

    Output:

    0.00289
    987.0
    0.418