Format value with Brazilian currency mask

12

I have a stored procedure that returns me a credit amount for a certain amount of consortium.

The return of this value would look like this: 167900 .

But it should look like this: R$ 167.900,00 .

This value I feed a <td> to a repeater , which I get this way:

<td><asp:Label ID="lblCreditoCota" runat="server" Text='<%# Eval("CreditoDisponivel") %>' /></td>

I would like to mask this value for the mask of Real (Brazil). How do I do this?

    
asked by anonymous 23.01.2015 / 12:12

1 answer

21

You can use string.Format , passing the C format):

<td>
    <asp:Label 
        ID="lblCreditoCota" 
        runat="server" 
        Text='<%# string.Format("{0:C}", Eval("CreditoDisponivel")) %>' />
</td>

Of course, this code simply uses the default currency display culture.

It is necessary to worry about the variation of the culture or it is necessary to display the monetary value in a currency other than that of the local culture. In this case you have to force the culture.

One way to force the culture using string.Format is:

var valorFormatado = string.Format(CultureInfo.GetCultureInfo("pt-BR"), "{0:C}", valor)

There is still a scenario where it is necessary to show a monetary value in foreign currency, but as it is showing for Brazilians, it is desired to use the culture of thousand and decimal separators of Brazilians.

In this case you can set the desired currency, format the number with the thousand and decimal separators, and inform the culture from which you want to get these tabs:

var valorFormatado = string.Format(CultureInfo.GetCultureInfo("pt-BR"), "US$ {0:#,###.##}", valor)

Finally, a cool solution that shows the foreign currency using the local culture tabs, regardless of which one this local culture:

// obtém a cultura local
var cultureInfo = Thread.CurrentThread.CurrentCulture; 
// faz uma cópia das informações de formatação de número da cultura local
var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
// fixa o símbolo da moeda estrangeira
numberFormatInfo.CurrencySymbol = "US$";
// obtém o valor em moeda estrangeira formatado conforme a cultura local
var valorFormatado = string.Format(numberFormatInfo, "{0:C}", valor);
    
23.01.2015 / 12:57