Django template: how to show decimal value as currency format with dollar sign, thousand separator with zero or two decimal points

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

Django template: how to show decimal value as currency format with dollar sign, thousand separator with zero or two decimal points

问题

在models.py中的字段是:

order_amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True)

如果order_amount的值是12345.67,如何在Django模板中显示它以满足以下两种格式:

  • 无小数点:$12,346
  • 带有两位小数:$12,345.67
英文:

The field in models.py is:

order_amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True)

if the order_amount value is 12345.67, how to display it in Django template for the below two formats:

  • without decimal point: $12,346
  • with two decimal points:
    $12,345.67

答案1

得分: 1

你可以使用内置的模板过滤器 floatformat(注意:数字会四舍五入而不是截取!)

${{value|floatformat:"2g"}}     987654321.987 -> 987,654,321.99
${{value|floatformat:"0g"}}     987654321.987 -> 987,654,322

参见:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#floatformat

英文:

you can use the built-in template filter floatformat (note: numbers are rounded not cut!)

${{value|floatformat:"2g"}}     987654321.987 -> 987,654,321.99
${{value|floatformat:"0g"}}     987654321.987 -> 987,654,322

see also: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#floatformat

huangapple
  • 本文由 发表于 2023年6月9日 08:20:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436452.html
匿名

发表评论

匿名网友

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

确定