How do I return a value in the Brazilian currency format in the Django view?

Asked

Viewed 16,210 times

12

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

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

6 answers

16


They have two simple ways to do that, next:

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 a local:

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

9

My strategy is simpler and more direct:

I use standard formatting ( same as dollar ) and just invert '.' and ',':

def real_br_money_mask(my_value):
    a = '{:,.2f}'.format(float(my_value))
    b = a.replace(',','v')
    c = b.replace('.',',')
    return c.replace('v','.')

inserir a descrição da imagem aqui

The cool thing about this approach is that you don’t have to do any import.

0

I was able to observe that the error was in the name "pt_BR.UTF-8". At least for my Python (3.6), to set the text format for Brazil, I used: "Portuguese_brazil.1252"

Follow my solution to your problem:

import locale
locale.setlocale(locale.LC_ALL, "Portuguese_Brazil.1252")
import matplotlib as mpl
mpl.rcParams['axes.formatter.use_locale'] = True

I hope it helps.

  • 1

    The value will depend on the operating system. Under Linux you can list possible values by running locale -a in the terminal.

0

With only one line of code and no matter what:

valor = 1768

valor_real = "R${:,.2f}".format(valor).replace(",", "X").replace(".", ",").replace("X", ".")

0

Using Python 3 in Windows 7 (already in en-BR), I found the following result:

inserir a descrição da imagem aqui

Using locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8'), resulted:

inserir a descrição da imagem aqui

However, I did not test with Python 2.

-1

To Format in Real without using function:

import locale
    
locale.setlocale(locale.LC_MONETARY, 'pt_BR.UTF-8')  
  
valor_em_Real_formatado = locale.currency(12.4593681)
print(valor_em_Real_formatado)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.