如何在德语语言环境中将字符串转换为Python十进制(用逗号代替点) [英] How do I convert a string to a Python Decimal in German locale (with comma instead of a point)

查看:97
本文介绍了如何在德语语言环境中将字符串转换为Python十进制(用逗号代替点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串转换为python十进制。

I'm trying to convert a string to a python decimal.

这有效

from decimal import *
mystr = '123.45'
print(Decimal(mystr))

但是当我想使用千位分隔符和语言环境时,它不是。
转换为float效果很好。

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

返回浮点数和错误

1234.56
InvalidOperation: [<class 'decimal.ConversionSyntax'>] 

是否有正确的方法来转换字符串,而无需通过float或hackier解决方案手动对其进行转换? FYA,我当前的hacky解决方案是:

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


推荐答案

我做了一些研究,下面是解决方法:

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 调用取消本地化函数,该函数完全可以执行@lsma的建议。

Under the hood locale.atof calls delocalize function which does exactly what @lsma suggests.

这篇关于如何在德语语言环境中将字符串转换为Python十进制(用逗号代替点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆