How to convert a string to a decimal decimal Python code in German (instead of a comma instead of a comma)

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}'))
+4
source share
3 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

locale.atof delocalize, , @lsma.

+5

, :

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)))
0

The locale options did not work for me, perhaps because I have very little on this machine along the path of internationalization, so I offer a solution based only on string manipulations:

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

Source: https://habr.com/ru/post/1684812/


All Articles