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
Release: 2024-12-02 07:52:09
Original
1021 people have browsed it

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')
Copy after login

However, this approach requires explicitly setting the locale to match the platform's settings:

locale.setlocale(locale.LC_ALL, '')
Copy after login

Locale from Environment

Alternatively, you can obtain locale settings from the environment:

locale.setlocale(locale.LC_ALL, "")
locale.atof("123,456.908")
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template