Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying prices

I'm getting prices in different currencies and want to display Brazilian R$ My formatting doesn't work and the display looks like this:

Price: 1.15..000.,00 R$

For good flexibility I've stored the price as a string: price=db.StringProperty(verbose_name="price")

I tried to implement my own filter and it didn't work: {{ ad.price|separate }} R$

def separate(n, sep='.'):
    ln = list(str(n))
    ln.reverse()
    newn = []
    while len(ln) > 3:
        newn.extend(ln[:3])
        newn.append(sep)
        ln = ln[3:]
    newn.extend(ln)
    newn.reverse()
    return "".join(newn)

Can you help me? Should I just remove the filter? Should I enforce some regex to the input instead? A link to my site is http://www.koolbusiness.com/servead/4252196

UPDATE: I'm considering using something like one of these filters:

import locale
locale.setlocale(locale.LC_ALL, '')

def currency(value): # doesn't work
    locale.setlocale(locale.LC_ALL, '')
    return locale.currency(value, grouping=True)

register.filter(currency)


def currencyWithoutUsingLocale(value): # needs adjustment
    value=float(value)
    symbol = '$' 
    thousand_sep = ''
    decimal_sep = ''
    # try to use settings if set 
    try:
        symbol = settings.CURRENCY_SYMBOL
    except AttributeError:
        pass

    try:
        thousand_sep = settings.THOUSAND_SEPARATOR
        decimal_sep = settings.DECIMAL_SEPARATOR
    except AttributeError:
        thousand_sep = ',' 
        decimal_sep = '.' 

    intstr = str(int(value))
    f = lambda x, n, acc=[]: f(x[:-n], n, [(x[-n:])]+acc) if x else acc
    intpart = thousand_sep.join(f(intstr, 3))
    return "%s%s%s%s" % (symbol, intpart, decimal_sep, ("%0.2f" % value)[-2:])

register.filter(currencyWithoutUsingLocale)
like image 724
Niklas Rosencrantz Avatar asked Aug 20 '26 19:08

Niklas Rosencrantz


1 Answers

Storing the price as a string is the first problem. It should be a Decimal. If you look at the Python standard library documentation for Decimal, you will see this http://docs.python.org/library/decimal.html#recipes

That moneyfmt recipe should do what you want

like image 144
Michael Dillon Avatar answered Aug 23 '26 12:08

Michael Dillon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!