Reputation: 5442
the following is my property where if we enter 45 then it appends 45.00 but then again it results in 45 because the value is converted from string. So what is the easiest way i can achieve this goal. Where if they enter 45 then it would result 45.00 in the value field;
public decimal Length
{
get { if (this is Detail)
return ((this as Detail).Length.ToString() == string.Empty)
? 0 : (this as Detail).Length; else return 0; }
set
{
if (this is Detail)
{
string val = string.Empty;
if (!value.ToString().Contains("."))
{
val = string.Format("{0}{1}", value.ToString(), ".00");
value =Math.Round(Convert.ToDecimal(val), 2);
}
else
value = Math.Round(value, 2);
(this as Detail).Length = (value.ToString().Trim() ==
string.Empty) ? 0 : value;
}
}
}
Upvotes: 0
Views: 413
Reputation: 15982
The problem is that 45m and 45.00m are the same thing, and since this is a decimal, it will always display "45" instead of "45.00" unless you use a string formatter every time you try to output it.
You could always make another property that does output what you want, such as:
public decimal Length { get; set; }
public string FormattedLength
{
get
{
return String.Format("{0:0.00}", this.Length);
}
}
On a side note I don't like this, but I believe it gets you more or less what you are looking for.
Upvotes: 0
Reputation: 27085
This has nothing to do with the property setter. You need to specify the string format in your GUI to round the numbers.
Also if (this is PersonalDetail)
is a massive design flaw. Override the Length property in the PersonalDetail class instead. (not sure what the intent is with this property)
Upvotes: 0