How can a decimal format to string in mvc avoiding

2019-08-29 23:42发布

问题:

I rounded the loan amount value. But in my model I have defined the Loan Amount as Decimal. In Grid I need to show it as an Integer (need to avoid the last two zero's after the point).

For example: it shows as 22.00 if the data saved is 21.50. In the grid I need to display as 22 only - avoiding the zeros after the point.

Code:

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

回答1:

You can create Helper method e.g. DisplayDecimal

public static class HtmlExtensionsView
{
    public static string DisplayDecimal(this HtmlHelper helper, decimal? input)
    {
        // you can do you rouding math here
    }
}

then in your .cshtml file you can call (referencing extension's namespace) @Html.DisplayDecimal(modelItem => item.LoanAmount)

More information about rounding in C# is available at http://msdn.microsoft.com/en-us/library/3s2d3xkk.aspx



回答2:

In your view you can simply add the following:

@string.Format("{0:#}", modelItem.LoanAmount)


回答3:

You can use DisplayFormat attribute to make it work as per your choice.. Just decorate your property with displayformat and provide appropriate format.

[DisplayFormat(DataFormatString = "YOUR_FORMAT")]
public decimal YourProperName {get;set;}