Welcome, guest | Sign In | My Account | Store | Cart

Convert comma separated floating point number (12,3456) to float.

Python, 18 lines
 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

5 comments

Larry Hastings 14 years, 2 months ago  # | flag

What's wrong with float(str(float_string).replace(",", "")) ?

Matevz Lesko (author) 14 years, 2 months ago  # | flag

Not working for me

>>> float_string = "1,25"
>>> float(str(float_string).replace(",", ""))
125.0
Akira Fora 14 years, 2 months ago  # | flag

Try float(float_string.replace(",","."))

Akira Fora 14 years, 2 months ago  # | flag

My bad, I did not cover all you test cases. This is better: float(float_string.replace(".","").replace(",","."))

Charlie Clark 14 years, 2 months ago  # | flag

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.

Created by Matevz Lesko on Thu, 11 Feb 2010 (MIT)
Python recipes (4591)
Matevz Lesko's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks