I am trying to convert a string to decimal decimal code.
It works
from decimal import *
mystr = '123.45'
print(Decimal(mystr))
But when I want to use the thousands separator and the locale, it is not. Converting to float works fine.
from locale import *
setlocale(LC_NUMERIC,'German_Germany.1252')
from decimal import *
mystr = '1.234,56'
print(atof(mystr))
print(Decimal(mystr))
returns float and error
1234.56
InvalidOperation: [<class 'decimal.ConversionSyntax'>]
Is there a correct way to convert a string without manually converting it via float or hacking solutions? FYA, my current hacker solution:
print(Decimal(f'{atof(mystr):2.2f}'))
source
share