简体   繁体   中英

Rounding a decimal in Jinja template Flask

I would like to round up a decimal value as a result of a division in Jinja template is there a way I can do this?
I have tried doing it like this:

<td>{{'%0.2f'|format(spend[0] / user[0] |float ) }}</td>

but I got an error:

TypeError: unsupported operand type(s) for /: 'decimal.Decimal' and 'float'

if the result of the division is for example:

666.6666666666666666666666667

it should be rounded to 666.67

Is there a way I can achieve this?

You do have two issues:

  • You seems to have mixed types in your variables (one decimal and one float), you should cast them both to float, prior to the division (as there is no decimal type in Jinja)
  • You are using a format filter when you want to round, there is, though, a round filter for that purpose

Given those two remarks, your snippet of code should be:

<td>
  {{ ((spend[0] | float) / (user[0] | float)) | round(2) }}
</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM