简体   繁体   中英

How to format negative currency numbers in Flask and jinja

In Flask/jinja I am trying to reformat a number in

  {{ "${:,.2f}".format(row['total']) }}

It is for buying/selling stocks so I would like the number to be presented as $1000 for bought and -$1000 for sold (bonus points if I can format the negative number in red too!)

The problem with the above formatting, it gives $1000 for a positive amount and $-1000 for a negative amount

Appreciate any help.

you can create your custom jinja2 filter.

for more organization, you can dedicate a separated file filters.py for all your custom jinja2 filters just like forms.py or models.py

in filters.py

from numbers import Number
from decimal import Decimal

from jinja2 import Markup


def format_currency(value):
    if not isinstance(value, (Number, Decimal)):
        raise TypeError("Value must be Number.")
    if value < 0:
        return Markup'<span style="color:red">- </span>' + format_currency(-value))
    return "${:,.2f}".format(value)

in your main file where you instantiate your Flask app, register you custom jinja2 filter like

from falsk import Flask, ...
from .filters import format_currency

..
app = Flask(__name__)

app.jinja_env.filters['format_currency'] = format_currency

..

in your template

<p>{{ 0 | format_currency }}</p>
<p>{{ 1000 | format_currency }}</p>
<p>{{ 1000.12654 | format_currency }}</p>
<p>{{ -1000 | format_currency }}</p>
<p>{{ 2151000 | format_currency }}</p>
<p>{{ -2151000 | format_currency }}</p>

and this will output:

$0.00
$1,000.00
$1,000.13
- $1,000.00
$2,151,000.00
- $2,151,000.00

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