Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 329
Toubi Avatar asked Oct 17 '13 06:10

Toubi


1 Answers

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

like image 85
Kamil Budziewski Avatar answered Sep 29 '22 10:09

Kamil Budziewski