11

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?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
StefanS
  • 261
  • 3
  • 4
  • 10

7 Answers7

24

The easy way is replace! One simple example:

value=str('6,0865000000e-01')
value2=value.replace(',', '.')
float(value2)
0.60865000000000002
juliomalegria
  • 24,229
  • 14
  • 73
  • 89
ederwander
  • 3,410
  • 1
  • 18
  • 23
11

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
9

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

print(format(the_float, '.8f'))
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
3

This work for me, try it out.

def remove_exponent(value):
    decial = value.split('e')
    ret_val = format(((float(decial[0]))*(10**int(decial[1]))), '.8f')
    return ret_val
prem
  • 39
  • 2
2

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)
happierall
  • 91
  • 4
2

Simply by casting string into float:

new_val = float('9.81E7')
0x3bfc
  • 2,715
  • 1
  • 16
  • 20
0

I had a similar issue trying to convert from string in scientific/exponential notation to a float number (that can result also in exponential notation if too long)

num = '-8e-05'

def scientific_to_float(exponential):
  split_word = 'e'
  e_index = exponential.index('e')
  base = float(exponential[:e_index])
  exponent = float(exponential[e_index + 1:])
  float_number = base * (10 ** exponent)
  return float_number

scientific_to_float(num) # return -8e-05 float number
federico
  • 340
  • 3
  • 11