I need to round off 4 digit decimal to 2 digits and show in MVC 3 UI
Something like this 58.8964 to 58.90
Tried following this How should I use EditorFor() in MVC for a currency/money type? but not working.
As i am using TextBoxFor=> i removed ApplyFormatInEditMode here. Even i tried with ApplyFormatInEditMode , but nothing works. Still showing me 58.8964.
MyModelClass
[DisplayFormat(DataFormatString = "{0:F2}")]
public decimal? TotalAmount { get; set; }
@Html.TextBoxFor(m=>m.TotalAmount)
How can i achieve this round off?
I can't use EditorFor(m=>m.TotalAmount) here, as i need to pass some htmlAttributes
Edit:
After debugging with MVC source code, they internally use
string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);
in MvcHtmlString InputHelper() method of InputExtension.cs that takes object value as parameter and converting. They are not using any display format there. How could we fix?
I managed to fix in this way. As i have a custom helper, i can able to manage with the below code
if (!string.IsNullOrEmpty(modelMetaData.DisplayFormatString))
{
string formatString = modelMetaData.DisplayFormatString;
string formattedValue = String.Format(CultureInfo.CurrentCulture, formatString, modelMetaData.Model);
string name = ExpressionHelper.GetExpressionText(expression);
string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
return htmlHelper.TextBox(fullName, formattedValue, htmlAttributes);
}
else
{
return htmlHelper.TextBoxFor(expression, htmlAttributes);
}
See Question&Answers more detail:os