在Python中将数字格式化为货币 [英] Format numbers as currency in Python
本文介绍了在Python中将数字格式化为货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从 Python中的货币格式中学习,请使用
I learn from Currency formatting in Python, use the locale module to format numbers as currency. For instance,
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import locale
value = 123456789
l = locale.setlocale(locale.LC_ALL, '') # LC_CTYPE=en_US.UTF-8;LC_NUMERIC=fr_FR.UTF-8;LC_TIME=fr_FR.UTF-8;LC_COLLATE=en_US.UTF-8;LC_MONETARY=fr_FR.UTF-8;LC_MESSAGES=en_US.UTF-8;LC_PAPER=fr_FR.UTF-8;LC_NAME=fr_FR.UTF-8;LC_ADDRESS=fr_FR.UTF-8;LC_TELEPHONE=fr_FR.UTF-8;LC_MEASUREMENT=fr_FR.UTF-8;LC_IDENTIFICATION=fr_FR.UTF-8
s = locale.currency(value, grouping=True) # 123 456 789,00 €
locale.setlocale(locale.LC_ALL, 'en_US.utf-8')
s = locale.currency(value, grouping=True) # $123,456,789.00
locale.setlocale(locale.LC_ALL, 'en_US') # WHY? locale.Error: unsupported locale setting
s = locale.currency(value, grouping=True)
我想将数字格式化为其他货币,例如de_DE
.我遇到问题locale.Error: unsupported locale setting
,因为语言环境de_DE
不在locale -a
的列表中.
I'd like to format numbers to other currency, say de_DE
. I encounter the issue locale.Error: unsupported locale setting
since the locale de_DE
is not in the list of locale -a
.
locale.setlocale(locale.LC_ALL, 'de_DE') # locale.Error: unsupported locale setting
s = locale.currency(value, grouping=True)
一种解决方案是将该语言环境添加到我的机器上.有更好的方法吗?
One solution is to add this locale to my machine. Is there a better way?
推荐答案
In [22]: from babel.numbers import format_decimal
In [23]: format_decimal(12345, locale='de_DE')
Out[23]: u'12.345'
In [24]: format_decimal(1.2345, locale='sv_SE')
Out[24]: u'1,234'
或者您的情况 format_currency :
In [7]: from babel.numbers import format_currency
In [8]: print format_currency(1099.98, 'USD', locale='en_US')
$1,099.98
In [9]: print format_currency(1099.98, 'USD', locale='es_CO')
1.099,98 US$
In [10]: print format_currency(1099.98, 'EUR', locale='de_DE')
1.099,98 €
这篇关于在Python中将数字格式化为货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文