Python: Convert string with comma separator and dot to float

avatar

Borislav Hadzhiev

Last updated: Sep 2, 2022

banner

Photo from Unsplash

Python: Convert string with comma separator and dot to float #

To convert a string with comma separator and dot to a float:

  1. Use the locale.setlocale() method to set the locale to en_US.UTF-8.
  2. Use the locale.atof() method to convert the string to a float.
main.py
import locale # ✅ Convert string with comma separator and dot to float (locale.atof()) locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') my_str = '456,789.4567' result = locale.atof(my_str) print(result) # 👉️ 456789.4567 # ------------------------------------------- # ✅ Convert string with comma separator and dot to float (str.replace()) result = float(my_str.replace(',', '')) print(result) # 👉️ 456789.4567

The first example uses the locale.atof() method to convert the string with a comma and dot to a float.

We used the locale.setlocale() method to set the locale to en_US.UTF-8.

main.py
import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

The setlocale() method takes the category and the locale.

The locale.LC_ALL category sets the locale for all categories.

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.

main.py
import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') my_str = '456,789.4567' result = locale.atof(my_str) print(result) # 👉️ 456789.4567
Make sure to use the setlocale() method before calling the locale.atof() method.

Alternatively, you can use the str.replace() method.

To convert a string with comma separator and dot to a float:

  1. Use the str.replace() method to remove the commas from the string.
  2. Use the float() class to convert the string to a floating-point number.
main.py
my_str = '456,789.4567' result = float(my_str.replace(',', '')) print(result) # 👉️ 456789.4567

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

The method doesn't change the original string. Strings are immutable in Python.

Once the commas are removed from the string, we can use the float() class to convert it to a floating-point number.

Note that in some locales a comma is used as the thousands separator (e.g. in the United States) and in some other locales a comma is used as the decimal separator (e.g. France).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.