[英]decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
I want to convert a dollar value to decimal for some simple math. 我想通过一些简单的数学将美元值转换为十进制。
Following python: how to convert currency to decimal? 以下python:如何将货币转换为十进制? I have: 我有:
def dollars_to_decimals(dollars):
from decimal import Decimal
return Decimal(dollars.strip('$'))
Now when I try: 现在,当我尝试:
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'>]
What am I doing wrong? 我究竟做错了什么?
You are dealing with localized data formats here. 您正在此处处理本地化的数据格式。 This is where using the locale module would help. 这是使用语言环境模块会有所帮助的地方。
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('$')))
Be sure to specify the locale for what you would expect. 确保指定所需的语言环境。 There are a list of windows codes at https://docs.microsoft.com/en-us/cpp/c-runtime-library/country-region-strings?view=vs-2019 在https://docs.microsoft.com/zh-cn/cpp/c-runtime-library/country-region-strings?view=vs-2019中有Windows代码列表
Also would be good to note that if you're using locale's "atoi" method, you probably wouldn't need the Decimal object. 还要注意,如果您使用语言环境的“ atoi”方法,则可能不需要Decimal对象。
You could consider just removing commas, but some latin languages use commas as the decimal placeholder, while other languages uses them as the thousands separator, so just removing non-numeric characters would possibly break your conversion 您可以考虑只删除逗号,但是某些拉丁语言使用逗号作为小数位占位符,而其他语言则将它们用作千位分隔符,因此仅删除非数字字符可能会破坏您的转换
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.