Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚡️ Speed up percentage() by 40% in posthog/templatetags/posthog_filters.py #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions posthog/templatetags/posthog_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,24 @@
@register.filter
def percentage(value: Optional[Number], decimals: int = 1) -> str:
"""
Returns a rounded formatted with a specific number of decimal digits and a % sign. Expects a decimal-based ratio.
Example:
{% percentage 0.2283113 %}
=> "22.8%"
"""
Returns a rounded formatted with a specific number of decimal digits and a % sign.

Parameters
----------
value : Optional[Number]
The number to be converted to a percentage.

if value is None:
return "-"
decimals : int, default=1
The number of decimal places to include in the formatted percentage.

return "{0:.{decimals}f}%".format(value * 100, decimals=decimals)
Returns
-------
str
Formatted percentage string or '-' if value is None.

Example
-------
>>> percentage(0.2283113)
'22.8%'
"""
return "-" if value is None else f"{value * 100:.{decimals}f}%"
Loading