简体   繁体   中英

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? 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

Also would be good to note that if you're using locale's "atoi" method, you probably wouldn't need the Decimal object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM