Question

I'm not sure of the limits of Jinja, so this might not be possible... I'm trying to calculate a percentage of two variables I've passed into Jinja, but I can't get it to round properly. What I'd like to have is something like:

{{ spygames / games|length * 100 | round(0) | int }}

Which gets the correct number (66.666666, since spygames is 2 and there are 3 games), but it renders as "66.6666666667" (I add the % sign in the html) and I want it to just be "67".

I've also tried this by getting the length of games in python and passing it in as a separate integer value, but it still has the same result.

How can I round this down to a whole number?

Thanks!

Was it helpful?

Solution

The Jinja documentation doesn't specify any precedence rules, but I strongly suspect that the filter is only applied to the 100 literal just before it.

Group your expressions to make sure that a filter is applied to the outcome of the expression:

{{ (spygames / games|length * 100) | round(0) | int }}

Personally, I'd use the str.format() function; it has a % percentage formatting option that includes multiplication by 100:

{{ '{:.0%}'.format(spygames / games|length) }}

This does add a percent sign to the output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top