如何将'$ 1,234.56'读取为1234.56 [重复项]

问题描述 投票:2回答:2

我已经浏览了'currency'线程,但是它们都是相反的方式。我正在阅读以$ 1,234.56&c格式输入的财务数据,其中包括所有字符串。我拆分了输入行,并希望将值项转换为浮点数以进行加/减(我很担心舍入错误)。当然,float()会引发错误。

我可以编写一个称为'amount = float(num(value_string))的函数,但是如果在32,000个Python模块之一中有一个“ dollar_string_to_float()”函数,则该命令会更麻烦。

python python-3.x currency
2个回答
1
投票

我认为这个问题与this question稍有不同,但我不确定。

无论如何,从上面提到的问题中得到的代码只需要将一个函数从Decimal更改为Float,并删除十进制导入即可。

根据您的要求,代码在dollar_string_to_float函数中:

>>> from re import sub

>>> def dollar_string_to_float(s):
        return float(sub(r'[^\d.]', '', money))


>>> money = '$1,234.56'
>>> print dollar_string_to_float(money)
1234.56

1
投票

查看正则表达式模块。您可以编译与美元/美分格式匹配的模式,并从中提取浮点数。

© www.soinside.com 2019 - 2024. All rights reserved.