Report helper (#6454)

* Adds helper function for formatting numbers in reports

* Update docs
This commit is contained in:
Oliver 2024-02-08 15:01:47 +11:00 committed by GitHub
parent 226dc82cfd
commit a99ba75fed
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 60 additions and 0 deletions

View File

@ -3,6 +3,7 @@
import base64 import base64
import logging import logging
import os import os
from decimal import Decimal
from django import template from django import template
from django.conf import settings from django.conf import settings
@ -376,3 +377,48 @@ def render_html_text(text: str, **kwargs):
output += ''.join([f'</{tag}>' for tag in tags]) output += ''.join([f'</{tag}>' for tag in tags])
return mark_safe(output) return mark_safe(output)
@register.simple_tag
def format_number(number, **kwargs):
"""Render a number with optional formatting options.
kwargs:
decimal_places: Number of decimal places to render
integer: Boolean, whether to render the number as an integer
leading: Number of leading zeros
"""
try:
number = Decimal(str(number))
except Exception:
# If the number cannot be converted to a Decimal, just return the original value
return str(number)
if kwargs.get('integer', False):
# Convert to integer
number = Decimal(int(number))
# Normalize the number (remove trailing zeroes)
number = number.normalize()
decimals = kwargs.get('decimal_places', None)
if decimals is not None:
try:
decimals = int(decimals)
number = round(number, decimals)
except ValueError:
pass
value = str(number)
leading = kwargs.get('leading', None)
if leading is not None:
try:
leading = int(leading)
value = '0' * leading + value
except ValueError:
pass
return value

View File

@ -64,6 +64,20 @@ To return an element corresponding to a certain key in a container which support
{% endraw %} {% endraw %}
``` ```
## Formatting Numbers
The helper function `format_number` allows for some common number formatting options. It takes a number (or a number-like string) as an input, as well as some formatting arguments. It returns a *string* containing the formatted number:
```html
{% raw %}
{% load report %}
{% format_number 3.14159265359 decimal_places=5, leading=3 %}
<!-- output: 0003.14159 -->
{% format_number 3.14159265359 integer=True %}
<!-- output: 3 -->
{% endraw %}
```
## Rendering Currency ## Rendering Currency
The helper function `render_currency` allows for simple rendering of currency data. This function can also convert the specified amount of currency into a different target currency: The helper function `render_currency` allows for simple rendering of currency data. This function can also convert the specified amount of currency into a different target currency: