Skip to content

Instantly share code, notes, and snippets.

@mooose
Created October 14, 2020 07:27
Show Gist options
  • Save mooose/6a0330acfaef27537075ba7e4f1c6d83 to your computer and use it in GitHub Desktop.
Save mooose/6a0330acfaef27537075ba7e4f1c6d83 to your computer and use it in GitHub Desktop.
Convert a strnig to float
def do_float(x):
"""convert a string into a float - float is in the front of the string
"""
if isinstance(x, int):
return float(x)
elif isinstance(x, float):
return x
else:
x = str(x)
try:
w = x.split()
for x in w:
try:
f = float(x)
return f
except:
continue
return 0.0
except:
# logging.info("do_float %s" % x)
return 0.0
def do_float_with_comma(x):
"""convert a string into a float - convert comma into dot first
"""
if isinstance(x, int):
return float(x)
else:
x = str(x)
try:
if "." in x and "," in x:
if x.index(".") < x.index(","):
# comma is more left than dot in string
x = x.replace(".", "", 1)
elif x.index(",") < x.index("."):
x = x.replace(",", "", 1)
x = x.replace(",", ".")
return do_float(x)
except:
# logging.info("do_float %s" % x)
return 0.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment