如何将欧元货币字符串转换为浮点数?

时间:2016-11-21 09:42:32

标签: python floating-point locale currency-formatting euro

我需要将Continental Europe格式的字符串货币字符串转换为浮点数:

输入:

'6.150.593,22 €'

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

输出:

6150593.22

我读过这些问题,但它们仅适用于美元货币和地区:

currency_euros='6.150.593,22 €' float(currency_euros[:-2]) Traceback (most recent call last): File "", line 1, in 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 个答案:

答案 0 :(得分:4)

使用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

答案 1 :(得分:0)

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))))

答案 2 :(得分:0)

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

>>> val = '6.150.593,22 €'
>>> res = val[:-2].split(',')
>>> float('.'.join([res[0].replace('.', ''), res[1]]))
6150593.22

答案 3 :(得分:0)

这样做的好方法(1行):

NewValue = float(value[:-2].replace(".", "").replace(",","."))