python – How to return a value in Brazilian currency format in Django view?

Question:

How to return 1768 value in BRL 1.768,00 currency format in Django view?

def moeda(request):
    valor = 1768
    # formata o valor
    return HttpResponse('Valor: %s' % valor)

Answer:

There are two simple ways to do this, as follows:

1) using locate:

from django.utils.formats import localize
def moeda(request):
    valor = 1768 
    valor = localize(valor)
    return HttpResponse('Valor: %s' % valor)
    # resultado: Valor: 1.768,00

2) using locale:

import locale
def moeda(request):
    valor = 1768 
    locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
    valor = locale.currency(valor, grouping=True, symbol=None)
    return HttpResponse('Valor: %s' % valor)
    # resultado: Valor: 1.768,00
Scroll to Top