Better methods to convert this numeric string with commas to float in python?

336 views Asked by At

I am using python v3. I have this string 1,027.86. I want to convert it to float 1027.86.

I found a solution while googling.

import locale
locale.setlocale(locale.LC_NUMERIC, "nl")
price = '1,027.86'
price = locale.atof(price)*1000

I searched the documentation on what locale.setlocale(locale.LC_NUMERIC, "nl") means but could not find an answer. http://dc.dyu.edu.tw/python/350/library/locale.html

Is there a better argument to put inside setlocal() that will return the result directly without the need of multiplying by 1000 later?

2

There are 2 answers

0
Martin Evans On BEST ANSWER

Specifying nl for setlocale() is telling it to default to the format for the Netherlands. If you use something like uk it should convert correctly as the numeric format is of the formxxx,xxx,xxx.xxx.

import locale

locale.setlocale(locale.LC_NUMERIC, "uk")
price = '1,027.86'
print(locale.atof(price))

This would display:

1027.86
0
Jonesinator On

You can use a simple string replacement to turn it into a float that can be properly parsed price = float('1,027.86'.replace(',','')).