3

I've Googled and searched here but can't find an explanation I understand. I've got a value which gets passed into the html template with the value 53.0 which is obtained from a 3rd party API.

My code is:

£{{product_details.UnitPrice}}

Which displays £53.0, is there a way of formatting this as a 2 decimal place float so it correctly reads £53.00.

I have tried reading some instructions here from the github but I don't understand them. I'm trying to avoid formatting each variable separately in my actual Python code or is that the wrong approach?

I'm editing the question because the per my comment:

£{{product_details.UnitPrice|float}}

Didn't make any difference and I don't understand the link given.

Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50
  • Take a look at this answer: https://stackoverflow.com/a/11260267/7090605 – Jake Conway Sep 10 '17 at 19:38
  • I've already read that and it doesn't make sense for my context. £{{product_details.UnitPrice|float}} makes no difference. – Johnny John Boy Sep 10 '17 at 19:43
  • 2
    Take a look at the specific answer I linked - it mentioned doing this instead: `{{'%0.2f'| format(proc_err|float)}}%`. In the context of this question, it would look like `£{{'%0.2f'|format(product_details.UnitPrice|float)}}`. – Jake Conway Sep 10 '17 at 19:45
  • 1
    Thank you Jake, that does solve the problem but doesn't help me understand what's happening here or other possible options. In the github it says "The format filter as implemented in jinja2 is redundant anyway. If I could, I would deprecate and finally remove it, but mitsuhiko would not let me break backwards compatibility. Whenever I have to format a string in a template, I use the modulo operator inline." I don't understand the correct way of doing this. – Johnny John Boy Sep 10 '17 at 19:49
  • 1
    It looks like the way to use the modulo operator inline would be something like this: `£{{'%0.2f' % product_details.UnitPrice}}`. – Jake Conway Sep 10 '17 at 19:55

2 Answers2

14

Thanks to Jake who explained

{{'%0.2f'|format(product_details.UnitPrice|float)}}

Is the correct format to get 2 decimal places.

Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50
0

Try this:

{{ "£{:,.2f}".format(product_details.UnitPrice) }}

atwalsh
  • 3,622
  • 1
  • 19
  • 38