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

formatting a decimal as percentage to display in view?


In MVC Razor view, a decimal field is required to be displayed as percentage BUT without percentage sign. For example 2 or 2.5

I understand it can be from model and it will be something like:

    [AutoMapIgnore]
    [DisplayFormat(DataFormatString = "{0:F1}")]
    public virtual decimal OffPeakMarginPercent { get { return OffPeakMargin * 100; } }

But is not doing any effecting at all, currently it is being displayed as:

Currently it is being displayed as 3.00000 or 2.50000.

Can you please guide.

I highly appriciate your guidance and help.

Edit:

If I format in view as below, it displays as 3.0 or 2.5

@row.OffPeakMarginPercent.ToString("0.0")

Solution

  • change

    [DisplayFormat(DataFormatString = "{0:F1}")]
    

    to

    [DisplayFormat(DataFormatString = "{0:P2}")]
    

    and remove *100 from getter

    as said here format for percentages in decimal is P not F