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

被刻印的时光 ゝ 提交于 2020-06-11 18:09:51

问题


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}'))

回答1:


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.




回答2:


Here is an idea, basically we format the string according the locale before converting:

from locale import *
from decimal import *

def format_decimal(s):
   return '{0:n}'.format(s)

setlocale(LC_NUMERIC,'German_Germany.1252')
thousandSep = localeconv()['thousands_sep']
decimalPoint = localeconv()['decimal_point']
mystr = '1.234,56'.replace(thousandSep, '').replace(decimalPoint, '.')
print(atof(mystr))
print(format_decimal(Decimal(mystr)))



回答3:


The locale options didn't work for me, perhaps because I have very little on this machine in the way of internationalization, so I offer a solution that relies only on string manipulation:

numbr = 1234.56

mystr = '{:,.2f}'.format(numbr) # Ugly American format
mystr_orig = mystr # Ugly (but saved for later!) American format

mystr = mystr.replace(',', '{0}')
mystr = mystr.replace('.', '{1}')

print(mystr_orig)
print(mystr.format('.', ','))


来源:https://stackoverflow.com/questions/45980030/how-do-i-convert-a-string-to-a-python-decimal-in-german-locale-with-comma-inste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!