Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string to a Python Decimal in German locale (with comma instead of a point)

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}'))
like image 619
576i Avatar asked Aug 31 '17 11:08

576i


People also ask

How do you convert text to a decimal in Python?

If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','. '))

How do you convert a string to a decimal with two decimal places in Python?

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.

How do you convert a string to a comma with a float in Python?

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.


1 Answers

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.

like image 127
newtover Avatar answered Nov 16 '22 02:11

newtover