atof returns could not convert string to float: '2, 5'

Viewed 639

I'm trying to understand the atof method, however, the block below fails with the error in topic title:

 import locale
 s='2,5'
 x=locale.atof(s)

What can I do?

2 Answers

You actually have to SET the locale to a place where , is the numeric separator, not just import the module. That category is LC_NUMERIC:

import locale
s='2,5'
locale.setlocale(locale.LC_NUMERIC, 'de_DE')  # 'de_DE' is just an example
x=locale.atof(s)

Or if you OS environment is set to a locale where , is the numeric separator you can usually do as recommended in the locale documentation of:

import locale
locale.setlocale(locale.LC_ALL, '')

This sets the locale for all categories to the user’s default setting (typically specified in the LANG environment variable).

You aren't setting the locale - so I don't know what it might be defaulting to; presumably the system default.

Try this :

 import locale
 locale.setlocale(locale.LC_ALL, '')
 s='2,5'
 x=locale.atof(s)

This will set the locale for all categories to your users default.

Does that work ?

Related