In this
topic I will show examples on how to format your string, decimal/double or
integer value in currency with C#. While working on any application it is always
good to show user more human friendly money format rather than showing simple
value.
Formatting
currency is quite easy with C#. We’ll use the standard Currency (“C”) Format
Specifier, it works like this: {0:C}.
//declare amount.
decimal amount =
1704.40m;
string currency = string.Format("{0:C}", amount);
We can
get same result with the help of ToString() method like:
string currency = amount.ToString("C");
Output
in both case will be:
$1,704.40
|
We can
also get output in different currency symbol (e.g. ₹ $ £ ₩ € etc.) using culture information.
With the
help of “CultureInfo.CreateSpecificCulture("culuture-name")“ one can set the culture
information, and can print the price with the proper currency symbol.
For
example:
For
Indian Currency:
string.Format(CultureInfo.CreateSpecificCulture("hi-IN"), "{0:C}", amount);
Output: ₹ 1,704.40
For
United States Currency:
string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C}", amount);
Output: $1,704.40
For
British Pound Currency:
string.Format(CultureInfo.CreateSpecificCulture("en-GB"), "{0:C}", amount);
Output: £1,704.40
For
European Euro Currency(you can use French culuture):
string.Format(CultureInfo.CreateSpecificCulture("fr-FR"), "{0:C}", amount);
Output: 1 704.40 €
|
Same way
you can format currency value with other cultures, you can found all available culture
names from here.
“It’s
recommended to use numeric value for formatting, because if you try to format
string value, it won’t format correctly. If your currency value is in a
string, you need to convert it into a double or decimal before formatting.”
|
Hope it
helps J
Comments
Post a Comment