83

I am using Flask/Jinja2 template to show a number using |float filter.

Here is my code

{% set proc_err = nb_err|length / sum * 100 %}
({{proc_err|float}}%)

Output is a bit awkward:

17/189 (8.99470899471%)

I am looking for a way to make the places after dot limited to a number e.g. 2.

Desired output:

17/189 (8.99%)
Paolo
  • 20,112
  • 21
  • 72
  • 113
Blaise
  • 7,230
  • 6
  • 43
  • 53

4 Answers4

104

It turns to be quite simple:

My code:

{% set proc_err = nb_err|length / sum * 100 %}
({{proc_err|float}}%)

Can be changed a bit with:

{% set proc_err = nb_err|length / sum * 100 %}
({{'%0.2f' % proc_err|float}}%)

or using format:

({{'%0.2f'| format(proc_err|float)}}%)

Reference can be found here on jinja2 github issue 70

Blaise
  • 7,230
  • 6
  • 43
  • 53
  • Is there a way to set a certain precision (like 0.3f) as a default in the current template? Just to avoid repetition ? – GertVdE Apr 12 '19 at 12:45
86

You can use round to format a float to a given precision.

Extracted from the docs:

round(value, precision=0, method='common')

Round the number to a given precision. The first parameter specifies the precision (default is 0), the second the rounding method:

  • common rounds either up or down
  • ceil always rounds up
  • floor always rounds down

If you don’t specify a method common is used.

{{ 42.55|round }}
    -> 43.0
{{ 42.55|round(1, 'floor') }}
    -> 42.5

Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through int:

{{ 42.55|round|int }}
    -> 43
Paolo Casciello
  • 7,982
  • 1
  • 43
  • 42
  • 2
    Except that `round(2)` will not return '42.00' ever, even if you have to serialize a `Decimal()` value. – lol Jan 07 '17 at 07:07
  • @lol the question is about rounding not formatting. Even if the OP wanted the formatting. Printing decimals deals also with locales. Rounding is a mathematical operation while printing a formatted value is only visual. In OP question though is better to print 100% than 100.00% ;) – Paolo Casciello Jan 07 '17 at 09:51
  • Yes you are correct, and have caught me dropping an embarrassing sneaky hack into the codebase. Lol! – lol Jan 09 '17 at 22:52
37

Here is one approach ::

{{ "%.2f"|format(result) }}

Tweak it as you like :)

Akash Kandpal
  • 3,126
  • 28
  • 25
-3

(I'm assuming you use to Ionic v2)

Use this front-end code:

<div *ngIf="device.usage > 0">
   {{ Round(device.usage)}} min  
</div>

and put the following function into the .ts file:

Round(number):number
{
    return parseFloat(Number((number/1000) / 60).toFixed(2)); 
}
Njol
  • 3,271
  • 17
  • 32
Mohamathu Rafi
  • 115
  • 1
  • 2