Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use float filter to show just two digits after decimal point?

Tags:

flask

jinja2

wsgi

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%) 
like image 685
Blaise Avatar asked Jun 29 '12 10:06

Blaise


People also ask

How do I restrict float to 2 decimal places?

We will use %. 2f to limit a given floating-point number to two decimal places.

How do I show only 2 digits after the decimal in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

How do I restrict a float value to only two places after the decimal point in Java?

Using the format() method "%. 2f" denotes 2 decimal places, "%. 3f" denotes 3 decimal places, and so on. Hence in the format argument, we can mention the limit of the decimal places.


2 Answers

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

like image 70
Blaise Avatar answered Sep 23 '22 04:09

Blaise


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 
like image 23
Paolo Casciello Avatar answered Sep 21 '22 04:09

Paolo Casciello