Convert comma separated floating point number (12,3456) to float.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def myfloat(float_string):
"""It takes a float string ("1,23" or "1,234.567.890") and
converts it to floating point number (1.23 or 1.234567890).
"""
float_string = str(float_string)
errormsg = "ValueError: Input must be decimal or integer string"
try:
if float_string.count(".") == 1 and float_string.count(",") == 0:
return float(float_string)
else:
midle_string = list(float_string)
while midle_string.count(".") != 0:
midle_string.remove(".")
out_string = str.replace("".join(midle_string), ",", ".")
return float(out_string)
except ValueError, error:
print "%s\n%s" %(errormsg, error)
return None
|
What's wrong with float(str(float_string).replace(",", "")) ?
Not working for me
Try float(float_string.replace(",","."))
My bad, I did not cover all you test cases. This is better: float(float_string.replace(".","").replace(",","."))
There is already string.atof and locale.atof for handling different decimals points.
"1,234.567.890" is not be a number so this should fail any conversion from a formatted string to a number. If you have an application that needs coercion of such strings it might be better to use a regular expression to handle the punctuation to remove all punctuation but the last example of the relevant decimal point.