2016-11-21 45 views
-1

我需要在歐洲大陸格式的字符串的貨幣字符串轉換成浮點數:如何將歐元貨幣字符串轉換爲浮動號碼?

輸入:

'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 €' 
>>> 

我ashtonished是locale.currency()工作正常,但它的倒數方法locale.atof()不起作用。

+0

只需刪除所有點並用逗號替換逗號一個點。去除非浮點字符 –

+0

查看'locale'模塊。 https://docs.python.org/3/library/locale.html –

+0

是的,我知道如何消除字符串的Eur(€)符號,但此時,問題在於locale.atof()doesn不支持貨幣符號字符。 – Trimax

回答

3

使用locale.atofhttps://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 
+0

感謝您向我展示'locale.atof()'方法,但它不會不能使用de Eur(€)符號,而locale.currency()這個倒數方法似乎支持它。我更新了我的問題。 – Trimax

+0

''atof''用於解析一個數字。任何貨幣符號不是實際數量的一部分。這取決於情況和應用程序如何表示!例如,在某些系統中,我在前面或末尾遇到歐元,或在前面或末尾遇到「歐元」,被一個或多個標籤和/或空格隔開。這取決於你我想剝離貨幣符號,所以你只能將實際的數字字符串傳遞給'atof''。 –

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

一個簡單的解決方案可以是如下:

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

這樣做(1行)的一個好方法:

NewValue = float(value[:-2].replace(".", "").replace(",",".")) 
相關問題