Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
762 views
Welcome To Ask or Share your Answers For Others

1 Answer

This works in MVC5

@Html.TextBoxFor(m => m.TotalAmount, "{0:0.00}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...