Monday, October 24, 2022

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

Issue

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

Solution

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.



Answered By - newtover
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.