Search code examples
pythonpython-3.xlocalesetlocale

Better methods to convert this numeric string with commas to float in python?


I am using python v3. I have this string 1,027.86. I want to convert it to float 1027.86.

I found a solution while googling.

import locale
locale.setlocale(locale.LC_NUMERIC, "nl")
price = '1,027.86'
price = locale.atof(price)*1000

I searched the documentation on what locale.setlocale(locale.LC_NUMERIC, "nl") means but could not find an answer. http://dc.dyu.edu.tw/python/350/library/locale.html

Is there a better argument to put inside setlocal() that will return the result directly without the need of multiplying by 1000 later?


Solution

  • Specifying nl for setlocale() is telling it to default to the format for the Netherlands. If you use something like uk it should convert correctly as the numeric format is of the formxxx,xxx,xxx.xxx.

    import locale
    
    locale.setlocale(locale.LC_NUMERIC, "uk")
    price = '1,027.86'
    print(locale.atof(price))
    

    This would display:

    1027.86