我正在获取不同货币的价格并希望显示巴西 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/