Answer the question
In order to leave comments, you need to log in
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'
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question