How can I convert a string with dot and comma into a float in Python

kevinlu picture kevinlu · Jul 9, 2011 · Viewed 183.3k times · Source

How can I convert a string like 123,456.908 to float 123456.908 in Python?

Answer

Karl Knechtel picture Karl Knechtel · Jul 9, 2011

... Or instead of treating the commas as garbage to be filtered out, we could treat the overall string as a localized formatting of the float, and use the localization services:

from locale import atof, setlocale, LC_NUMERIC
setlocale(LC_NUMERIC, '') # set to your default locale; for me this is
# 'English_Canada.1252'. Or you could explicitly specify a locale in which floats
# are formatted the way that you describe, if that's not how your locale works :)
atof('123,456') # 123456.0
# To demonstrate, let's explicitly try a locale in which the comma is a
# decimal point:
setlocale(LC_NUMERIC, 'French_Canada.1252')
atof('123,456') # 123.456