I want to format the value in the getter and return a formated currency value.
Is this possible or do i need to declare the property as a string and then use string.format.
I want to format the value in the getter and return a formated currency value.
Is this possible or do i need to declare the property as a string and then use string.format.
A decimal type can not contain formatting information. You can create another property, say FormattedProperty
of a string type that does what you want.
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);
}
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:
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");
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.
}