Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting exponential to float

This is my code, trying to convert the second field of the line from exponential into float.

outputrrd = processrrd.communicate()
(output, error) = outputrrd
output_lines = output.split('\n')
for line in output_lines:
    m = re.search(r"(.*): ", line)
    if m != None:
        felder = line.split(': ')
        epoch =  felder[0].strip(':')
        utc = epoch2normal(epoch).strip("\n")
        #print felder[1]
        data = float(felder[1])
        float_data = data * 10000000
        print float_data
        resultslist.append( utc + ' ' + hostname + ' ' +  float_data)

But, the program stops with this error:

File "/opt/omd/scripts/python/livestatus/rrdfetch-convert.py", line 156, in <module>
    data = float(felder[1])
ValueError: invalid literal for float(): 6,0865000000e-01

Does anyone know the reason?

like image 794
StefanS Avatar asked Feb 08 '12 14:02

StefanS


People also ask

How do I get rid of E+ in Python?

How do you stop e+ in Python? Use a string literal to suppress scientific notation Use the string literal syntax f"{num:. nf}" to represent num in decimal format with n places following the decimal point.


4 Answers

The easy way is replace! One simple example:

value=str('6,0865000000e-01')
value2=value.replace(',', '.')
float(value2)
0.60865000000000002
like image 139
ederwander Avatar answered Sep 20 '22 01:09

ederwander


The reason is the use of comma in 6,0865000000e-01. This won't work because float() is not locale-aware. See PEP 331 for details.

Try locale.atof(), or replace the comma with a dot.

like image 43
NPE Avatar answered Sep 21 '22 01:09

NPE


The float is correct, just use format to display it as you want, i.e.:

print(format(the_float, '.8f'))
like image 41
Pedro Lobito Avatar answered Sep 22 '22 01:09

Pedro Lobito


I think it is useful to you:

def remove_exponent(value):
    """
       >>>(Decimal('5E+3'))
       Decimal('5000.00000000')
    """
    decimal_places = 8
    max_digits = 16

    if isinstance(value, decimal.Decimal):
        context = decimal.getcontext().copy()
        context.prec = max_digits
        return "{0:f}".format(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
    else:
        return "%.*f" % (decimal_places, value)
like image 24
happierall Avatar answered Sep 20 '22 01:09

happierall