-->

How do I convert a string to a Python Decimal in G

2020-08-17 18:11发布

问题:

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('.', ','))