2

我需要将欧洲大陆格式的字符串货币字符串转换为浮点数:

输入:

'6.150.593,22 €'

意识到小数点是逗号,千位分隔符是句点字符。

输出:

6150593.22

我读过这些问题,但它们仅适用于美元货币和语言环境:

currency_euros='6.150.593,22 €'
float(currency_euros[:-2])
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    float(currency_euros[:-2])
ValueError: could not convert string to float: '6.150.593,22'

更新:在@IrmendeJong 回答之后:

>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, "es")
'es'
>>> print(locale.currency(6150593.22))
6150593,22 €
>>> money = '6.150.593,22 €'
>>> locale.atof(money)
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    locale.atof(money)
  File "C:\Python35\lib\locale.py", line 318, in atof
    return func(delocalize(string))
ValueError: could not convert string to float: '6150593.22 €'
>>> 

我很高兴这locale.currency()很好,但它的倒数方法locale.atof()不起作用。

4

4 回答 4

7

使用locale.atof https://docs.python.org/3/library/locale.html#locale.atof

>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC,"nl")
'nl'
>>> locale.atof("6.150.593,22")
6150593.22
于 2016-11-21T09:50:20.077 回答
3

一个很好的方法(1行):

NewValue = float(value[:-2].replace(".", "").replace(",","."))
于 2016-11-21T11:19:24.280 回答
1
value = '6.150.593,22 €'
value = value.split()[0]              #Take out euro symbol
integer, decimal = value.split(',')   #Separate integer and decimals
integer = integer.replace('.','')     #Take out dots
final_value = int(integer) + (int(decimal) * (10**(-len(decimal))))
于 2016-11-21T09:51:07.610 回答
1

一个简单的解决方案可能如下:

>>> val = '6.150.593,22 €'
>>> res = val[:-2].split(',')
>>> float('.'.join([res[0].replace('.', ''), res[1]]))
6150593.22
于 2016-11-21T09:54:50.313 回答