Home >Backend Development >Python Tutorial >How to Safely Convert Locale-Specific String Numbers to Floats in Python?

How to Safely Convert Locale-Specific String Numbers to Floats in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 07:52:09943browse

How to Safely Convert Locale-Specific String Numbers to Floats in Python?

How to Convert a String with Dot and Comma into a Float in Python

Using Localization Services

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

Caveats

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn