Home >Backend Development >Python Tutorial >How to Safely Convert Locale-Specific String Numbers to Floats in Python?
Default Locale
The Python locale module offers an interface to C-based localization routines.
import locale locale.atof('123,456.908')
However, this approach requires explicitly setting the locale to match the platform's settings:
locale.setlocale(locale.LC_ALL, '')
Locale from Environment
Alternatively, you can obtain locale settings from the environment:
locale.setlocale(locale.LC_ALL, "") locale.atof("123,456.908")
Explicit Locale Setting
You can also specify a specific locale by name:
locale.setlocale(locale.LC_NUMERIC, 'en_DK.UTF-8') locale.atof('123,456.789') # Returns 123.456789 with period as thousands separator
Setting the locale globally affects the entire program and should be done with caution. Extension modules should not call setlocale().
The above is the detailed content of How to Safely Convert Locale-Specific String Numbers to Floats in Python?. For more information, please follow other related articles on the PHP Chinese website!