python - 显示价格

标签 python django currency

我正在获取不同货币的价格并希望显示巴西 R$ 我的格式设置不起作用,显示如下:

价格:1.15..000.,00 雷亚尔

为了更好的灵 active ,我将价格存储为字符串:price=db.StringProperty(verbose_name="price")

我尝试实现自己的过滤器,但没有成功: {{ 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)

你能帮帮我吗?我应该只删除过滤器吗?我应该对输入强制执行一些正则表达式吗?我网站的链接是 http://www.koolbusiness.com/servead/4252196

更新:我正在考虑使用类似以下过滤器之一的东西:

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)

最佳答案

将价格存储为字符串是第一个问题。它应该是十进制。如果你查看 Decimal 的 Python 标准库文档,你会看到这个 http://docs.python.org/library/decimal.html#recipes

那个 moneyfmt 配方应该做你想做的事

关于python - 显示价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6880447/

相关文章:

python - 仅提取属于特定 kmeans 标签的样本

python - 给 Python 终端一个持久的历史

javascript - 从另一个选择框填充一个选择框并使用数据库连接

python - Django:在 clean() 方法中获取以前的值

python - 如何在 Django 模板中获取我网站的域名?

javascript - REGEX 在 MVC4 Razor/Javascript 中使用上标格式化小数

python - 从数组中的每一列减去不同的数字

python - 尝试理解神经网络

Golang : how can I convert a float64 currency representation to the lowest denomination?(乘以 100 不适用于所有货币)

excel - 在单元格中强制使用美国货币(或其他国家/地区)