PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

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

 October 24, 2022     decimal, python, python-3.x, type-conversion     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing