Format value with Brazilian currency mask

Asked

Viewed 41,651 times

14

I have a stored trial that returns a credit amount for a certain consortium quota.

The return of that value would be like this: 167900.

But it should be so: R$ 167.900,00.

This value I feed a <td> in a repeater, which I take this way:

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

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

1 answer

30


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

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

Of course this code simply uses the standard culture for currency display.

Eventually 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 need to force the culture.

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

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

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

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

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

Finally, a very nice solution that shows foreign currency using local culture tabs, regardless of what this local culture is:

// 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);

Browser other questions tagged

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