Search code examples
c#asp.net-mvcformattingstring-formatting

DataFormatString for percent with decimals only when needed?


I am trying to use these on EF code first properties with MVC: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Specifically:

[DisplayFormat(DataFormatString="##.##%")]
public double? PercentOfSomething {get;set;}

How do I get .2345 to display as 23.45% and .2 to display as 20% In other words, only show the decimal, up to two places, if there is one.

As it is now, it just displays the format string "##.##%". I am guessing maybe these types of format strings are not supported by the DisplayFormat attribute.


Solution

  • I think you should use "{0:##.##%}" instead of just ##.##%