Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Formatting to Currency C#

Tags:

c#

asp.net

I am new to building web applications in ASP.NET and am trying to display a currency in Kenya Shillings. The symbol for the shilling is KES.

I have this:

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

Culture name sourced from http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.80%29.aspx.

However, the price shows as S3,000 instead of KES 3,000.

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

like image 324
Kinyanjui Kamau Avatar asked Apr 03 '14 11:04

Kinyanjui Kamau


People also ask

What is %s in string format?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.

What type of number format is used to display values as a currency?

If you want to display numbers as monetary values, you must format those numbers as currency. To do this, you apply either the Currency or Accounting number format to the cells that you want to format. The number formatting options are available on the Home tab, in the Number group.

What is N0 in C#?

ToString("N0") is supposed to print the value with comma separators and no decimal points.


3 Answers

If the format is not as you expect you can add custom string formatting:

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

Hope this works.

like image 173
Michael Mairegger Avatar answered Nov 14 '22 05:11

Michael Mairegger


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

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

to get the correct CurrencySymbol for your culture.

//edit: Or you can try this function:

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

}

Which gives you a formatted currency string based on the current UICulture.

like image 24
TheCutter Avatar answered Nov 14 '22 05:11

TheCutter


If your machine's regional settings are properly set then you can use:

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

It will automatically take culture based on your machine's regional settings.

like image 1
Palak.Maheria Avatar answered Nov 14 '22 07:11

Palak.Maheria