How can I format decimal property to currency?

129,806

Solution 1

Properties can return anything they want to, but it's going to need to return the correct type.

private decimal _amount;

public string FormattedAmount
{
    get { return string.Format("{0:C}", _amount); }
}

Question was asked... what if it was a nullable decimal.

private decimal? _amount;

public string FormattedAmount
{
    get
    {
         return _amount == null ? "null" : string.Format("{0:C}", _amount.Value);
    }
}  

Solution 2

Below would also work, but you cannot put in the getter of a decimal property. The getter of a decimal property can only return a decimal, for which formatting does not apply.

decimal moneyvalue = 1921.39m; 
string currencyValue = moneyvalue.ToString("C");

Solution 3

Try this;

  string.Format(new CultureInfo("en-SG", false), "{0:c0}", 123423.083234);

It will convert 123423.083234 to $1,23,423 format.

Solution 4

You can create an extension method. I find this to be a good practice as you may need to lock down a currency display regardless of the browser setting. For instance you may want to display $5,000.00 always instead of 5 000,00 $ (#CanadaProblems)

public static class DecimalExtensions
{
    public static string ToCurrency(this decimal decimalValue)
    {
        return $"{decimalValue:C}";
    }
}

Solution 5

You can use String.Format, see the code [via How-to Geek]:

decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
// Output: $1,921.39

See also:

Share:
129,806

Related videos on Youtube

WingMan20-10
Author by

WingMan20-10

Updated on July 05, 2022

Comments

  • WingMan20-10
    WingMan20-10 almost 2 years

    I want to format a decimal value as a currency value.

    How can I do this?

  • Groppe
    Groppe about 8 years
    What happens if the amount is a nullable decimal?
  • Yves Rochon
    Yves Rochon over 6 years
    You can also specify the number of desired decimal places after the letter C, for example, if your value was 12.123 and you only wanted 2 decimal places in the output, you can use String.Format("{0:C2}", _amount.Value. Furthermore, you can specify a IFormatProvider if you want your string to be formatted to a specific culture.
  • siride
    siride about 2 years
    This doesn't make any sense. It's currency so why would the value be in a DatetimeOffset object?
  • Ira
    Ira about 2 years
    Thanks for pointing out after your comment I realized I used decimal for Amount and used Datetimeoffset for the date field.