如何将欧元货币字符串转换为浮点数? [英] How to convert Euro currency string to float number?

查看:126
本文介绍了如何将欧元货币字符串转换为浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to convert a string currency string in Continental Europe format into a float number:

输入:

'6.150.593,22 €'

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

Realize that decimal point is comma, and thousands separators are period characters.

输出:

6150593.22

我会阅读以下问题,但它们仅适用于美元货币和语言环境:

I'd read these questions, but they only works for US dollar currency and locale:

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答案:

Updated: Following the @IrmendeJong answer:

>>> 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()不起作用.

I'm ashtonished that locale.currency() works fine but its reciprocal method locale.atof() doesn't work.

推荐答案

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

这篇关于如何将欧元货币字符串转换为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆