I'm trying to convert a string to a python decimal.
This works
from decimal import *
mystr = '123.45'
print(Decimal(mystr))
But when I want to use the thousand separator and the locale, it doesn't. 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 the float and an error
1234.56
InvalidOperation: [<class 'decimal.ConversionSyntax'>]
Is there a right way to convert the string without manually transforming it via float or hackier solutions? FYA, my current hacky solution is:
print(Decimal(f'{atof(mystr):2.2f}'))
If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','. '))
Just use float("3") to achieve that but notice that a float does not have a specific number of digits after the decimal point; that's more a feature of outputting a float using string formatting. So you can use '%. 2f' % float("3") to see your float value with two decimal digits.
To convert a string with comma separator and dot to a float:Use the str. replace() method to remove the commas from the string. Use the float() class to convert the string to a floating-point number.
I did some research and here is the solution:
import decimal
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
mystr = '1.234,56'
num = locale.atof(mystr, decimal.Decimal)
print('{}'.format(num))
print('{:n}'.format(num))
1234.56
1.234,56
Under the hood locale.atof
calls delocalize function which does exactly what @lsma suggests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With