将Django中的DecimalField格式化为货币金额。

huangapple go评论79阅读模式
英文:

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 &lt;b&gt;locale.format(&lt;/b&gt;'&euro; %.2f', self.amount, grouping=True, monetary=True&lt;b&gt;)&lt;/b&gt;&lt;/code&gt;&lt;/pre&gt;

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, &#39;de_DE.utf8&#39;)
    return &lt;b&gt;locale.format(&lt;/b&gt;&#39;&amp;euro; %.2f&#39;, self.amount, grouping=True, monetary=True&lt;b&gt;)&lt;/b&gt;&lt;/code&gt;&lt;/pre&gt;

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

huangapple
  • 本文由 发表于 2023年6月8日 01:16:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定