Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Decimal truncated to 2 decimal places on edit

I'm running MVC3 with Razor and noticed that decimal values are truncated to 2 decimal places when in edit mode. I've managed to get round it by annotating my property with a display format. This doesn't seem like a very good solution as I'll have to remember to do this for every new view I generate (or update my templates).

I have checked the value returned by our service to the controller and it is correct at 1.144, but when bound to the view it comes out as 1.14 in the TextBox

ViewModel Property

[Required] [Display(Name = "Unit Price")] public decimal UnitPrice { get; set; } 

.cshtml Code

@Html.LabelFor(model => model.UnitPrice)  @Html.EditorFor(model => model.UnitPrice)  @Html.ValidationMessageFor(model => model.UnitPrice) 

If I decorate the property with the following then it works.

[DisplayFormat(                ApplyFormatInEditMode = true,                 DataFormatString = "{0:0.00###########################}",                 NullDisplayText = "")] 

Any Ideas?

like image 423
Craig Avatar asked Mar 25 '11 03:03

Craig


People also ask

How do you set decimal places to 2?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do you truncate a double to two decimal places?

Shift the decimal of the given value to the given decimal point by multiplying 10^n. Take the floor of the number and divide the number by 10^n. The final value is the truncated value.


1 Answers

That's how the default Decimal editor template is defined:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <script runat="server">     private object ModelValue {         get {             if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model) {                 return String.Format(                     System.Globalization.CultureInfo.CurrentCulture,                     "{0:0.00}", ViewData.ModelMetadata.Model                 );             }             return ViewData.TemplateInfo.FormattedModelValue;         }     } </script> <%= Html.TextBox("", ModelValue, new { @class = "text-box single-line" }) %> 

Notice the {0:0.00} format.

So you have two possibilities:

  1. Use double instead of decimal as type in your model
  2. Modify the default editor template by creating a custom ~/Views/Shared/EditorTemplates/Decimal.cshtml which might simply look like this:

    @Html.TextBox(     "",      ViewData.TemplateInfo.FormattedModelValue,      new { @class = "text-box single-line" } ) 

You probably might want to modify the display template as well.

like image 59
Darin Dimitrov Avatar answered Oct 01 '22 14:10

Darin Dimitrov