How can I convert a string with dot and comma into a float in Python
Just remove the ,
with replace()
:
float("123,456.908".replace(',',''))
If you don't know the locale and you want to parse any kind of number, use this parseNumber(text)
function. It is not perfect but take into account most cases :
>>> parseNumber("a 125,00 €")
125
>>> parseNumber("100.000,000")
100000
>>> parseNumber("100 000,000")
100000
>>> parseNumber("100,000,000")
100000000
>>> parseNumber("100 000 000")
100000000
>>> parseNumber("100.001 001")
100.001
>>> parseNumber("$.3")
0.3
>>> parseNumber(".003")
0.003
>>> parseNumber(".003 55")
0.003
>>> parseNumber("3 005")
3005
>>> parseNumber("1.190,00 €")
1190
>>> parseNumber("1190,00 €")
1190
>>> parseNumber("1,190.00 €")
1190
>>> parseNumber("$1190.00")
1190
>>> parseNumber("$1 190.99")
1190.99
>>> parseNumber("1 000 000.3")
1000000.3
>>> parseNumber("1 0002,1.2")
10002.1
>>> parseNumber("")
>>> parseNumber(None)
>>> parseNumber(1)
1
>>> parseNumber(1.1)
1.1
>>> parseNumber("rrr1,.2o")
1
>>> parseNumber("rrr ,.o")
>>> parseNumber("rrr1rrr")
1
... 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