Toubi
Toubi

Reputation: 2509

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")

Upvotes: 15

Views: 23719

Answers (3)

Aladein
Aladein

Reputation: 312

in MVC 5 You can Change the index View If you want Just To show Two zeros After double Value

code Befor

  @Html.DisplayFor(modelItem => item.PRSPrice)

code After

 @Convert.ToDouble(item.PRSPrice.Value).ToString("0.00")

Thank You

Upvotes: 1

Carlos Landeras
Carlos Landeras

Reputation: 11063

Use

[RegularExpression(@"^\d+(\.\d)?$", ErrorMessage = "Only one decimal point value allowed")]
[Range( 0.1,100)]
public virtual decimal OffPeakMarginPercent { get { return OffPeakMargin * 100; } }

Upvotes: 0

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

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

Upvotes: 21

Related Questions