Formatting strings in C # currency

I am new to creating web applications in ASP.NET and am trying to display currencies in Kenyan shillings. The symbol for shilling is KES.

I have it:

<span>
    <b>Price: </b><%#:String.Format(new System.Globalization.CultureInfo("sw-KE"), "{0:c}", Item.BeatPrice)%> 
</span>

The name of the culture is obtained from http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.80%29.aspx .

However, the price is displayed as S3,000instead KES 3,000.

What do I need to do to correctly format the price?

+4
source share
6 answers

It's better not to hardcode CurrencySymbol, so you should use

var regionInfo = new RegionInfo("sw-KE");
var currencySymbol = regionInfo.ISOCurrencySymbol;

to get the right CurrencySymbol for your culture.

//: :

public static string FormatCurrency(decimal value)
{
    CultureInfo cultureInfo = Thread.CurrentThread.CurrentUICulture;
    RegionInfo regionInfo = new RegionInfo(cultureInfo.LCID);
    string formattedCurrency = String.Format("{0} {1:C}", regionInfo.ISOCurrencySymbol, value);
    return formattedCurrency.Replace(cultureInfo.NumberFormat.CurrencySymbol, String.Empty).Trim();

}

UICulture.

+3

, , :

String.Format("KES {0:N3}", Item.BeatPrice)

, .

+3

, :

Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0:c}", Item.BeatPrice));

.

+1

Ondrej Svejdar, , $ :

var region = new System.Globalization.RegionInfo("sw-KE");

Console.WriteLine(region.CurrencySymbol);  // "S"
Console.WriteLine(region.ISOCurrencySymbol);  // "KES"

: IDEone ( Mono), ( "KES" "Kenyan Shilling" ).

+1

String.Format "c" "C" . ISO Kenya Shillings. , .

String.Format("{0} {1}", (new RegionInfo("sw-KE")).ISOCurrencySymbol, Item.BeatPrice)

, .

String.Format("{0} {1}", "KES", Item.BeatPrice)
+1

String to Currency {0:C} UICulture Culture KES, ASP.NET , , culuture.

Note: You can change the culture by changing the culture of the browser (you can do this for development purposes), but best practice changes the culture programmatically, for example, here I change the culture to the user. Cookie and mu default culture is en-us like this.

protected override void InitializeCulture()
{
    HttpCookie cultureCookie = Request.Cookies["culture"];

    if (cultureCookie == null)
    {
        cultureCookie = new HttpCookie("culture", "en-US");
        Response.Cookies.Add(cultureCookie);
    }

    Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureCookie.Value);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureCookie.Value);

    base.InitializeCulture();
}
0
source

Source: https://habr.com/ru/post/1534817/


All Articles