英文:
Django formatting DecimalField to money
问题
在我的Django项目中,我在一个DecimalField中保存了金额。问题是当我打印它时,数字的格式不对。我需要它按照德国货币格式显示,即10.000,00 €,所以使用点作为分隔符,用逗号表示小数部分。在Django中,我只能将所有内容用逗号分隔,如10,000,00。
有人有想法如何按照我想要的方式实现吗?
英文:
In my Django project I'm saving a money amount in a decimalField. The problem is the format of the number when I print it. I need it in the german money format 10.000,00 € so first a point as seperator and a comma for the cents. In Django I've only managed it to seperate everything with commas like 10,000,00
Has anyone an idea how I can implement it as I want?
答案1
得分: 1
"Probably the cleanest way will be to format this with the locale
. First check if the German locale
is supported on your system, for example with Debian:
$ locale -a
this will list all locale's, the name can vary over different systems. If the locale does not appear, you can generate one with:
$ sudo locale-gen de_DE
$ sudo locale-gen de_DE.utf8
$ sudo update-locale
Now we can work with this locale to format the number:
<pre><code>import locale
class MyModel(models.Model):
amount = models.DecimalField(max_digits=12, decimal_places=2)
@property
def as_money(self):
locale.setlocale(local.LC_ALL, 'de_DE.utf8')
return <b>locale.format(</b>'€ %.2f', self.amount, grouping=True, monetary=True<b>)</b></code></pre>
You can then use this with a MyModel
object my_model
with my_model.as_money
.
Normally the currency sign is put in front of the amount, to prevent people from writing digits in front (whereas writing digits at the end is often less of a problem)."
英文:
Probably the cleanest way will be to format this with the locale
. First check if the German locale
is supported on your system, for example with Debian:
$ locale -a
this will list all locale's, the name can very over different system. If the locale does not appear, you can generate one with:
$ sudo locale-gen de_DE
$ sudo locale-gen de_DE.utf8
$ sudo update-locale
Now we can work with this locale to format the number:
<pre><code>import locale
class MyModel(models.Model):
amount = models.DecimalField(max_digits=12, decimal_places=2)
@property
def as_money(self):
locale.setlocale(local.LC_ALL, 'de_DE.utf8')
return <b>locale.format(</b>'&euro; %.2f', self.amount, grouping=True, monetary=True<b>)</b></code></pre>
You can then use this with a MyModel
object my_model
with my_model.as_money
.
Normally the currency sign is put in front of the amount, to prevent people from writing digits in front (whereas writing digits at the end is often less of a problem).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论