我想要将美元值转换为小数,以便进行一些简单的数学运算。
下面是我的python: how to convert currency to decimal?:
def dollars_to_decimals(dollars):
from decimal import Decimal
return Decimal(dollars.strip('$'))
现在当我尝试的时候:
Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] on win32
my_item['price']
'$24,900'
x = my_item['price']
type(x)
<class 'str'>
dollars_to_decimals(x)
Traceback (most recent call last):
File "C:\PYCHARM\helpers\pydev\_pydevd_bundle\pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<input>", line 1, in <module>
File "....\parsing.py", line 26, in dollars_to_decimals
return Decimal(dollars.strip('$'))
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
我做错了什么?
发布于 2019-07-09 02:48:18
您在这里处理的是本地化的数据格式。这就是使用locale模块会有所帮助的地方。
from decimal import Decimal
import locale
# if using *nix
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
# if using Windows
locale.setlocale(locale.LC_ALL, 'USA')
def dollars_to_decimals(dollars):
return Decimal(locale.atoi(dollars.strip('$')))
请确保指定您所期望的语言环境。在https://docs.microsoft.com/en-us/cpp/c-runtime-library/country-region-strings?view=vs-2019上有一个windows代码列表
同样值得注意的是,如果您使用的是locale的"atoi“方法,则可能不需要Decimal对象。
您可以考虑只删除逗号,但一些拉丁语言使用逗号作为小数占位符,而其他语言使用逗号作为千位分隔符,因此只删除非数字字符可能会中断转换
https://stackoverflow.com/questions/56940767
复制相似问题