Convert Python strings to float explicitly using comma or dot as delimiters

How can I explicitly tell python to read a decimal number using a period or comma as a decimal separator? I do not know the localization settings on the PC that will run my script, and this should not affect my application, I just want to say:

f = read_float_with_point("3.14") 

or

 f = read_float_with_comma("3,14") 

I think write

 def read_float_with_comma(num): return float(num.replace(",", ".") 

not safe because I don’t know the locale settings!

+8
source share
3 answers

because I don’t know the locale settings

You can see this with the locale module :

 >>> locale.nl_langinfo(locale.RADIXCHAR) '.' 

or

 >>> locale.localeconv()['decimal_point'] '.' 

Using this, your code could become:

 import locale _locale_radix = locale.localeconv()['decimal_point'] def read_float_with_comma(num): if _locale_radix != '.': num = num.replace(_locale_radix, ".") return float(num) 

Even better, the same module has a conversion function for you called atof() :

 import locale def read_float_with_comma(num): return locale.atof(num) 
+10
source

You can use locale.atof

 import locale locale.atof('12.3') 

http://docs.python.org/2/library/locale.html

+5
source

You can use babel to parse decimals in local formats:

 >>> parse_decimal('1,099.98', locale='en_US') Decimal('1099.98') >>> parse_decimal('1.099,98', locale='de') Decimal('1099.98') 
+1
source

All Articles