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(',',''))
Discussions

python - How to format a float with a comma as decimal separator in an f-string? - Stack Overflow
For some machine control in python, I write the results to a text-file, that someone else can copy into Excel (this is the most convenient way in this situation). However, in the Netherlands, Excel... More on stackoverflow.com
🌐 stackoverflow.com
How to use python with comma (,) instead of dot (.) as decimal separator?

You convert it before printing.

>>> print(str(3.5).replace(".",","))
3,5

Above code converts 3.5 to string, then replaces dot with comma.

More on reddit.com
🌐 r/learnpython
5
2
June 5, 2020
localization - Convert Python strings into floats explicitly using the comma or the point as separators - Stack Overflow
How can I explicitly tell python to read a decimal number using the point or the comma as a decimal separator? I don't know the localization settings of the PC that will run my script, and this should not influence my application, I only want to say: ... import locale _locale_radix = locale.localeconv()['decimal_point'] def read_float_with... More on stackoverflow.com
🌐 stackoverflow.com
Polars - Cast string to int, number with comma being null
What about this? def str_to_float(s): return int(float(s.replace(",", ""))) (df .with_column( pl .col('column') .apply(str_to_float))) More on reddit.com
🌐 r/learnpython
5
0
February 6, 2023
🌐
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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-string-with-comma-to-float-in-python
Convert String with Comma To Float in Python - GeeksforGeeks
July 23, 2025 - Below, are the ways to Convert a String With a Comma Separator And Dot To Float in Python.
🌐
Finxter
blog.finxter.com › home › learn python blog › python convert float to string
Python Convert Float to String - Be on the Right Side of Change
March 9, 2024 - The most Pythonic way to convert a float to a string is to pass the float into the built-in str() function. For example, str(1.23) converts the float 1.23 to the string '1.23'. Here’s a minimal example: Python Float to String Precision (Decimals) To set the decimal precision after the comma, ...
🌐
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
January 19, 2024 - NumPy is a core library for scientific computing in Python that provides a high-performance multidimensional array object. You can leverage NumPy to perform numeric conversions of strings even when they include commas. Here’s a quick way to accomplish this: import numpy as np # Your comma-separated string str_num = "1,234,567.89" # Replace commas and convert to float using NumPy float_num = np.float64(str_num.replace(',', '')) print(float_num)
Find elsewhere
🌐
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'
🌐
Python Guides
pythonguides.com › convert-string-to-float-in-python
Convert String With Comma To Float In Python: 3 Easy Methods
April 22, 2025 - The numbers were formatted with commas as thousand separators (like “1,234.56”), but Python’s float() function wouldn’t accept them directly. This is a common challenge when dealing with real-world data. In this article, I’ll show you three useful methods to convert comma-separated strings to float values in Python.
🌐
ActiveState
code.activestate.com › recipes › 577054-comma-float-to-float
"Comma float" to float « Python recipes « ActiveState Code
February 11, 2010 - 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 ·
🌐
GeeksforGeeks
geeksforgeeks.org › convert-string-float-to-float-list-in-python
Convert String Float to Float List in Python | GeeksforGeeks
February 6, 2025 - But problem arises when float values are in form of strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + Exception Handling ... Converting each item in a list to a string is a common task when working with data in Python.
🌐
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 ...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-convert-string-with-comma-separator-and-dot-to-float
Python: Convert string with comma separator and dot to float | bobbyhadz
The thousands separator character in the United States is a comma, so that's what we set the locale parameter to. The locale.atof() method takes a string and converts it to a floating-point number.
🌐
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
🌐
Herrmann
herrmann.tech › en › blog › 2021 › 02 › 05 › how-to-deal-with-international-data-formats-in-python.html
How to deal with international data formats in Python – herrmann.tech
February 5, 2021 - Comma (,) Both (may vary by location or other factors) Arabic decimal separator (٫) Data unavailable Map by NuclearVacuum on Wikipedia · What people often do when interpreting those numbers with Python is simply using the replace method of the str class. In [1]: number = '12,75' In [2]: parsed = float(number.replace(',', '.')) In [3]: parsed Out[3]: 12.75 ·
🌐
Altcademy
altcademy.com › blog › how-to-convert-string-to-float-in-python
How to convert string to float in Python - Altcademy.com
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
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python convert string to float
Python Convert String to Float - Spark By {Examples}
May 21, 2024 - Extremely large or small numbers may lose precision. For high-precision arithmetic, consider using libraries like decimal in Python. ... The float() function does not handle strings with commas representing thousands separators.