How can I format decimal property to currency?

前端 未结 8 1403
眼角桃花
眼角桃花 2020-12-02 21:50

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

How can I do this?

相关标签:
8条回答
  • 2020-12-02 22:20

    You can now use string interpolation and expression bodied properties in C# 6.

    private decimal _amount;
    
    public string FormattedAmount => $"{_amount:C}";
    
    0 讨论(0)
  • 2020-12-02 22:23

    Your returned format will be limited by the return type you declare. So yes, you can declare the property as a string and return the formatted value of something. In the "get" you can put whatever data retrieval code you need. So if you need to access some numeric value, simply put your return statement as:

        private decimal _myDecimalValue = 15.78m;
        public string MyFormattedValue
        {
            get { return _myDecimalValue.ToString("c"); }
            private set;  //makes this a 'read only' property.
        }
    
    0 讨论(0)
  • 2020-12-02 22:24

    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");
    
    0 讨论(0)
  • 2020-12-02 22:29

    Try this;

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

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

    0 讨论(0)
  • 2020-12-02 22:33

    A decimal type can not contain formatting information. You can create another property, say FormattedProperty of a string type that does what you want.

    0 讨论(0)
  • 2020-12-02 22:37

    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}";
        }
    }
    
    0 讨论(0)
提交回复
热议问题