public
Created

A python function to convert FORTRAN formatted float strings into floats

  • Download Gist
float.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import re
re_f_float_neg = re.compile('(-?[0-9.]*)(-\d\d\d)')
def fortran_float(input_string):
"""
Return a float of the input string, just like `float(input_string)`,
but allowing for Fortran's string formatting to screw it up when
you have very small numbers (like 0.31674-103 instead of 0.31674E-103 )
"""
try:
fl = float(input_string)
except ValueError,e:
match = re_f_float_neg.match(input_string.strip())
if match:
processed_string = match.group(1)+'E'+match.group(2)
fl = float(processed_string)
else:
print "Trying to find number from ",input_string
raise e
return fl

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.