在Python中是否有一种简单且首选的德语数字字符串格式设置方式? [英] Is there a simple and preferred way of German number string formatting in Python?

查看:59
本文介绍了在Python中是否有一种简单且首选的德语数字字符串格式设置方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Windows Windows上的Python中寻找正确的德语数字格式设置方式(例如 1.000,1234 ).

I am searching for the proper way of German number formatting (e.g. 1.000,1234) in Python under Windows OS.

我尝试了 locale.setlocale ,但没有成功.

I tried locale.setlocale but did not succeed.

相反,我编写了一个函数来提供所需的输出.

Instead, I have written a function to come up with the desired output.

有更好的方法吗?

def ger_num(number, precision=3):
    """
    returns german formatted number as string or an empty string
    """
    if number is not None:
        try:
            my_number = "{:,f}".format(number)
        except ValueError:
            return ""

        decimals, fraction = my_number.split(".")[0], my_number.split(".")[1]
        decimals = decimals.replace(",", ".")

        if precision:
            return decimals + "," + fraction[:precision]
        else:
            return decimals

    else:
        return ""

推荐答案

您可以使用 locale.setlocale 将语言环境设置为 de ,然后使用 locale.format 格式化您的电话号码:

You can use locale.setlocale to set the locale to de and then use locale.format to format your number:

import locale
locale.setlocale(locale.LC_ALL, 'de')
print(locale.format('%.4f', 1000.1234, 1))

这将输出:

1.000,1234

这篇关于在Python中是否有一种简单且首选的德语数字字符串格式设置方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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