Using the localization services

The default locale

The standard library locale module is Python's interface to C-based localization routines.

The basic usage is:

import locale
locale.atof('123,456')

In locales where , is treated as a thousands separator, this would return 123456.0; in locales where it is treated as a decimal point, it would return 123.456.

However, by default, this will not work:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/locale.py", line 326, in atof
    return func(delocalize(string))
ValueError: could not convert string to float: '123,456'

This is because by default, the program is "in a locale" that has nothing to do with the platform the code is running on, but is instead defined by the POSIX standard. As the documentation explains:

Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is. There is one exception: the LC_CTYPE category is changed at startup to set the current locale encoding to the user’s preferred locale encoding. The program must explicitly say that it wants the user’s preferred locale settings for other categories by calling setlocale(LC_ALL, '').

That is: aside from making a note of the system's default setting for the preferred character encoding in text files (nowadays, this will likely be UTF-8), by default, the locale module will interpret data the same way that Python itself does (via a locale named C, after the C programming language). locale.atof will do the same thing as float passed a string, and similarly locale.atoi will mimic int.

Using a locale from the environment

Making the setlocale call mentioned in the above quote from the documentation will pull in locale settings from the user's environment. Thus:

>>> import locale
>>> # passing an empty string asks for a locale configured on the
>>> # local machine; the return value indicates what that locale is.
>>> locale.setlocale(locale.LC_ALL, '')
'en_CA.UTF-8'
>>> locale.atof('123,456.789')
123456.789
>>> locale.atof('123456.789')
123456.789

The locale will not care if the thousands separators are in the right place - it just recognizes and filters them:

>>> locale.atof('12,34,56.789')
123456.789

In 3.6 and up, it will also not care about underscores, which are separately handled by the built-in float and int conversion:

>>> locale.atof('12_34_56.789')
123456.789

On the other side, the string format method, and f-strings, are locale-aware if the n format is used:

>>> f'{123456.789:.9n}' # `.9` specifies 9 significant figures
'123,456.789'

Without the previous setlocale call, the output would not have the comma.

Setting a locale explicitly

It is also possible to make temporary locale settings, using the appropriate locale name, and apply those settings only to a specific aspect of localization. To get localized parsing and formatting only for numbers, for example, use LC_NUMERIC rather than LC_ALL in the setlocale call.

Here are some examples:

>>> # in Denmark, periods are thousands separators and commas are decimal points
>>> locale.setlocale(locale.LC_NUMERIC, 'en_DK.UTF-8')
'en_DK.UTF-8'
>>> locale.atof('123,456.789')
123.456789
>>> # Formatting a number according to the Indian lakh/crore system:
>>> locale.setlocale(locale.LC_NUMERIC, 'en_IN.UTF-8')
'en_IN.UTF-8'
>>> f'{123456.789:9.9n}'
'1,23,456.789'

The necessary locale strings may depend on your operating system, and may require additional work to enable.

To get back to how Python behaves by default, use the C locale described previously, thus: locale.setlocale(locale.LC_ALL, 'C').

Caveats

Setting the locale affects program behaviour globally, and is not thread safe. If done at all, it should normally be done just once at the beginning of the program. Again quoting from documentation:

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored.

If, when coding a module for general use, you need a locale independent version of an operation that is affected by the locale (such as certain formats used with time.strftime()), you will have to find a way to do it without using the standard library routine. Even better is convincing yourself that using locale settings is okay. Only as a last resort should you document that your module is not compatible with non-C locale settings.

When the Python code is embedded within a C program, setting the locale can even affect the C code:

Extension modules should never call setlocale(), except to find out what the current locale is. But since the return value can only be used portably to restore it, that is not very useful (except perhaps to find out whether or not the locale is C).

(N.B: when setlocale is called with a single category argument, or with None - not an empty string - for the locale name, it does not change anything, and simply returns the name of the existing locale.)

So, this is not meant as a tool, in production code, to try out experimentally parsing or formatting data that was meant for different locales. The above examples are only examples to illustrate how the system works. For this purpose, seek a third-party internationalization library.

However, if the data is all formatted according to a specific locale, specifying that locale ahead of time will make it possible to use locale.atoi and locale.atof as drop-in replacements for int and float calls on string input.

Answer from Karl Knechtel on Stack Overflow
Top answer
1 of 10
210

Using the localization services

The default locale

The standard library locale module is Python's interface to C-based localization routines.

The basic usage is:

import locale
locale.atof('123,456')

In locales where , is treated as a thousands separator, this would return 123456.0; in locales where it is treated as a decimal point, it would return 123.456.

However, by default, this will not work:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/locale.py", line 326, in atof
    return func(delocalize(string))
ValueError: could not convert string to float: '123,456'

This is because by default, the program is "in a locale" that has nothing to do with the platform the code is running on, but is instead defined by the POSIX standard. As the documentation explains:

Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is. There is one exception: the LC_CTYPE category is changed at startup to set the current locale encoding to the user’s preferred locale encoding. The program must explicitly say that it wants the user’s preferred locale settings for other categories by calling setlocale(LC_ALL, '').

That is: aside from making a note of the system's default setting for the preferred character encoding in text files (nowadays, this will likely be UTF-8), by default, the locale module will interpret data the same way that Python itself does (via a locale named C, after the C programming language). locale.atof will do the same thing as float passed a string, and similarly locale.atoi will mimic int.

Using a locale from the environment

Making the setlocale call mentioned in the above quote from the documentation will pull in locale settings from the user's environment. Thus:

>>> import locale
>>> # passing an empty string asks for a locale configured on the
>>> # local machine; the return value indicates what that locale is.
>>> locale.setlocale(locale.LC_ALL, '')
'en_CA.UTF-8'
>>> locale.atof('123,456.789')
123456.789
>>> locale.atof('123456.789')
123456.789

The locale will not care if the thousands separators are in the right place - it just recognizes and filters them:

>>> locale.atof('12,34,56.789')
123456.789

In 3.6 and up, it will also not care about underscores, which are separately handled by the built-in float and int conversion:

>>> locale.atof('12_34_56.789')
123456.789

On the other side, the string format method, and f-strings, are locale-aware if the n format is used:

>>> f'{123456.789:.9n}' # `.9` specifies 9 significant figures
'123,456.789'

Without the previous setlocale call, the output would not have the comma.

Setting a locale explicitly

It is also possible to make temporary locale settings, using the appropriate locale name, and apply those settings only to a specific aspect of localization. To get localized parsing and formatting only for numbers, for example, use LC_NUMERIC rather than LC_ALL in the setlocale call.

Here are some examples:

>>> # in Denmark, periods are thousands separators and commas are decimal points
>>> locale.setlocale(locale.LC_NUMERIC, 'en_DK.UTF-8')
'en_DK.UTF-8'
>>> locale.atof('123,456.789')
123.456789
>>> # Formatting a number according to the Indian lakh/crore system:
>>> locale.setlocale(locale.LC_NUMERIC, 'en_IN.UTF-8')
'en_IN.UTF-8'
>>> f'{123456.789:9.9n}'
'1,23,456.789'

The necessary locale strings may depend on your operating system, and may require additional work to enable.

To get back to how Python behaves by default, use the C locale described previously, thus: locale.setlocale(locale.LC_ALL, 'C').

Caveats

Setting the locale affects program behaviour globally, and is not thread safe. If done at all, it should normally be done just once at the beginning of the program. Again quoting from documentation:

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored.

If, when coding a module for general use, you need a locale independent version of an operation that is affected by the locale (such as certain formats used with time.strftime()), you will have to find a way to do it without using the standard library routine. Even better is convincing yourself that using locale settings is okay. Only as a last resort should you document that your module is not compatible with non-C locale settings.

When the Python code is embedded within a C program, setting the locale can even affect the C code:

Extension modules should never call setlocale(), except to find out what the current locale is. But since the return value can only be used portably to restore it, that is not very useful (except perhaps to find out whether or not the locale is C).

(N.B: when setlocale is called with a single category argument, or with None - not an empty string - for the locale name, it does not change anything, and simply returns the name of the existing locale.)

So, this is not meant as a tool, in production code, to try out experimentally parsing or formatting data that was meant for different locales. The above examples are only examples to illustrate how the system works. For this purpose, seek a third-party internationalization library.

However, if the data is all formatted according to a specific locale, specifying that locale ahead of time will make it possible to use locale.atoi and locale.atof as drop-in replacements for int and float calls on string input.

2 of 10
205

Just remove the , with replace():

float("123,456.908".replace(',',''))
🌐
Finxter
blog.finxter.com › python-string-to-float-with-comma-easy-conversion-guide
Python String to Float with Comma: Easy Conversion Guide – Be on the Right Side of Change
You can use a combination of replace(), join(), split(), and even direct multiplication for more intricate string manipulation: str_with_comma = "12,345,678.90" # Remove commas and convert to float float_conversion = float(str_with_comma.replace(',', '')) # Split based on space or any other ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-string-with-comma-to-float-in-python
Convert String with Comma To Float in Python - GeeksforGeeks
July 23, 2025 - In this example, below Python code converts the numeric string "1,234.56" to a float by removing the comma and then prints the result.
🌐
Reddit
reddit.com › r/learnpython › converting string to float with "," as thousands separator
r/learnpython on Reddit: Converting string to float with "," as thousands separator
June 24, 2017 -
>>> float("123,000.12")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 123,000.12
>>> 

Is there a standard Pythonic way to convert string like "123,000.12" to float?

Regular float() and locale.atof() do not handle "," well.

🌐
ActiveState
code.activestate.com › recipes › 577054-comma-float-to-float
"Comma float" to float « Python recipes « ActiveState Code
Python, 18 lines · Download · Copy to clipboard · Tags: comma, float, numbers, string · Larry Hastings 14 years, 2 months ago # | flag · What's wrong with float(str(float_string).replace(",", "")) ? Matevz Lesko (author) 14 years, 2 months ago # | flag ·
🌐
Python Guides
pythonguides.com › convert-string-to-float-in-python
Convert String With Comma To Float In Python: 3 Easy Methods
April 22, 2025 - Read How To Convert JSON String To Dictionary In Python · Python’s locale module provides tools for working with different regional formatting. This is an elegant solution if you’re dealing with numbers in specific locales. import locale def locale_comma_to_float(string_value): # Set US locale (for comma as thousand separator) locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # Parse the string and convert to float return locale.atof(string_value) # Example usage try: price_string = "1,234.56" price_float = locale_comma_to_float(price_string) print(f"Original string: {price_string}") print(f"Converted float: {price_float}") except locale.Error: print("Locale not supported on this system.
🌐
Finxter
blog.finxter.com › 5-best-ways-to-convert-a-python-string-with-commas-to-float
5 Best Ways to Convert a Python String with Commas to Float – Be on the Right Side of Change
However, by ensuring that the input string is safely sanitized to contain only numeric characters and a single dot, it can convert the string to a float effectively. Method 1: replace() and float(). Strengths: Simple and straightforward. Weaknesses: Assumes format consistency and that commas ...
Find elsewhere
🌐
YouTube
youtube.com › watch
convert string number with comma to float python pandas - YouTube
Instantly Download or Run this code online at https://codegive.com Certainly! Below is a tutorial on how to convert a string number with commas to a float in...
Published   January 11, 2024
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-convert-string-to-float
How to Convert String to Float in Python: Complete Guide with Examples | DigitalOcean
July 10, 2025 - Here are two ways to handle this. For most cases, the simplest solution is to manipulate the string to a format that Python understands before you try to convert it. This involves two steps: Remove the thousands separators. Replace the comma decimal separator with a period.
🌐
Scaler
scaler.com › home › topics › how to convert string to float in python?
Convert String to Float in Python - Scaler Topics
May 5, 2022 - If we have the string which contains a comma such as 1,2.56, we can not directly convert the string to float using the float() function as there the condition was that the parameter should only be in integer or decimal form, so we would have ...
🌐
GitHub
gist.github.com › Keiku › b3e0038a2d1145ea82eda8444b98c02a
Convert number strings with commas in pandas DataFrame to float. · GitHub
Convert number strings with commas in pandas DataFrame to float. - convert_number_strings_to_numbers.py
🌐
Delft Stack
delftstack.com › home › howto › python › how to convert string to float or int
How to Convert String to Float or Int in Python | Delft Stack
February 2, 2024 - But commas are regularly used as either a thousand separator in countries like the US or UK, for example, 111,111.22, or decimal mark in most European countries, for example, 111,222. >>> float('111,111.22') Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> float('111,111.22') ValueError: could not convert string to float: '111,111.22' >>> float('111,111') Traceback (most recent call last): File "<pyshell#55>", line 1, in <module> float('111,111') ValueError: could not convert string to float: '111,111'
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python convert string to float
Python Convert String to Float - Spark By {Examples}
May 21, 2024 - # Quick examples of converting string to float # Method 1: Convert string to float using float() string_to_float = float("123.45") # Method 2: Convert string to float # Using the decimal module import decimal string_with_comma = "1,234.567" ...
🌐
Altcademy
altcademy.com › blog › how-to-convert-string-to-float-in-python
How to convert string to float in Python
June 13, 2023 - In this example, we first remove the thousands separator (comma) from the string_number using the replace() method and store the result in a variable called string_number_no_commas.
🌐
Medium
medium.com › @ryan_forrester_ › converting-strings-to-floats-in-python-a-complete-guide-f0ec19bf30a0
Converting Strings to Floats in Python: A Complete Guide | by ryan | Medium
October 28, 2024 - def safe_float_convert(value): try: return float(value) except ValueError: return None except TypeError: return None # Testing the function with different inputs examples = [ "123.45", # Valid float "invalid", # Invalid string None, # None value "12,345.67", # Comma-separated number ] for example in examples: result = safe_float_convert(example) print(f"Converting {example}: {result}") # Output: # Converting 123.45: 123.45 # Converting invalid: None # Converting None: None # Converting 12,345.67: None
🌐
GeeksforGeeks
geeksforgeeks.org › convert-string-float-to-float-list-in-python
Convert String Float to Float List in Python | GeeksforGeeks
February 6, 2025 - One such can be working with FORTRAN which can give text output (without spaces, which are required) '12.4567.23' . In this, there are actually two floating point separate numbers but concatenated. We can have problem in w ... Given a list enclosed within a string (or quotes), write a Python program to convert the given string to list type.
🌐
GitHub
github.com › bobbyhadz › python-convert-string-with-comma-separator-and-dot-to-float
GitHub - bobbyhadz/python-convert-string-with-comma-separator-and-dot-to-float: A repository for an article at https://bobbyhadz.com/blog/python-convert-string-with-comma-separator-and-dot-to-float
A repository for an article at https://bobbyhadz.com/blog/python-convert-string-with-comma-separator-and-dot-to-float - bobbyhadz/python-convert-string-with-comma-separator-and-dot-to-float
Author   bobbyhadz