Created
March 31, 2011 20:02
-
-
Save rwest/897137 to your computer and use it in GitHub Desktop.
A python function to convert FORTRAN formatted float strings into floats
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment