Posts with tag: Formatting

Format Currency in C#

2017-01-04 17:00 

Two methods for formatting currency in C#. 

The purpose being that you can throw a string containging a number in it and get out a nicely formatted string containing something you can present to a user.

Example of output.

var amountParsed = FormatCurrency("3123", "USD", true, "Not Known");
> 3 123 USD

var amountParsed = FormatCurrency("31.3", "USD", true, "Not Known");
> 31.30 USD

var amountParsed = FormatCurrency("12343", "USD", false, "Not Known");
> 12 343 USD

var amountParsed = FormatCurrency("XXX", "USD", false, "Not Known");
> Not Known

 

Code:

private static string FormatCurrency(string decimalStringValue, string currency, bool includeDecimals, string emptyPlaceHolder)
{
    if (string.IsNullOrEmpty(decimalStringValue) == false)
    {
        decimal decResult = 0;
        try
        {
            if (decimal.TryParse(decimalStringValue.Trim(), out decResult))
            {
                string formatted = FormatCurrency(decResult, currency, includeDecimals);
                return formatted;
            }
        }
        catch (Exception) {}
    }

    return emptyPlaceHolder;

private static string FormatCurrency(decimal decimalValue, string currency, bool includeDecimals)
{
    if (string.IsNullOrEmpty(currency))
        currency = "SEK";
 
    var decimalTemp = Math.Round(decimalValue, 2);
    var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
    nfi.NumberGroupSeparator = " ";
    string formatted = decimalTemp.ToString("#,0.00", nfi);
    if (includeDecimals == false)
    {
        if (formatted.LastIndexOf('.') >= 0)
            formatted = formatted.Substring(0, formatted.LastIndexOf('.'));
    }
 
    formatted = formatted.Trim() + " " + currency;
    return formatted.Trim();
}