[Tutor] ValueError: could not convert string to float: '13,2'

eryksun eryksun at gmail.com
Fri Jan 3 18:49:48 CET 2014


On Fri, Jan 3, 2014 at 11:53 AM, emile <emile at fenx.com> wrote:
> On 12/31/2013 12:56 PM, Mark Lawrence wrote:
>>
>> import locale
>>
>> # Set to users preferred locale:
>> locale.setlocale(locale.LC_ALL, '')
>> # Or a specific locale:
>> locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")
>> print(locale.atof("3,14"))
>
> This is a good solution, but be aware that it could impact other parts of
> your porgram as well, particularly if this is a read in data set from a
> non-local region.  Also, in places where commas are used as decimal points,
> it's also common to use periods as commas:
>
>>>> print(locale.atof("123.456,14"))
> 123456.14

If you're writing a library, don't modify the process locale. That's
for an application to set, preferably only once at startup. Use some
other library such as ICU:

    >>> import icu

    >>> lc = icu.Locale.createCanonical('da_DK.utf-8')
    >>> lc.getDisplayLanguage()
    'Danish'
    >>> lc.getDisplayCountry()
    'Denmark'

    >>> nf = icu.NumberFormat.createInstance(lc)
    >>> nf.parse('123.456,14').getDouble()
    123456.14

http://userguide.icu-project.org/locale
http://userguide.icu-project.org/formatparse/numbers


More information about the Tutor mailing list