P
P
pcdesign2020-08-26 14:20:05
Python
pcdesign, 2020-08-26 14:20:05

What is the correct and universal solution for rounding in jinja2?

In jinja2 I need to round numbers like:

1.5555 -> 1.55
1.5 -> 1.5
1.0 -> 1
1 -> 1
50 -> 50
50.00 -> 50
0.3222 -> 0.32

I found a thread on SO about this:
https:// stackoverflow.com/questions/28458524/how-t...

But between us, writing such a huge construction for such purposes is clearly not comme il faut:

import jinja2
>>> jinja2.Template('''{{ (50|float|round(2)|string).rstrip('0').rstrip('.') }}''').render()
'50'
>>> jinja2.Template('''{{ (5.58|float|round(2)|string).rstrip('0').rstrip('.') }}''').render()
'5.58'


There's also an option to put it into a function. And on a python already to solve this problem. But the implementation itself raises questions.

Can eat a variant to implement all this more beautifully?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gennady S, 2020-08-26
@pcdesign

Heh just add your filter: https://jinja.palletsprojects.com/en/2.11.x/api/#c... it's a healthy practice.

def smart_round(text: str, ndigits: int = 2) -> str:
    try:
        number = round(float(text), ndigits)
        if number == int(number):
            number = int(number)
        return str(number)
    except: # строка не является float / int
        return ''

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question