I have a property of my model that is of type double. One of my elements has a value of 0.000028, but when my editable view is displayed, the editor for this value is displayed as 2.8e-005.
Besides the fact that it confuses my users, it also does not allow me to check the correctness of the expression
[Display(Name = "Neck Dimension")] [RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "Neck Dimension must be a Number")] [Range(0, 9999.99, ErrorMessage = "Value must be between 0 - 9,999.99")] [Required(ErrorMessage = "The Neck Dimension is required.")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:F20}")] public double? NeckDimension { get; set; }
How do I display this field? I have this bit of code (shown below) that will display the decimal number as I want, but I'm not sure where to implement it.
var dbltest = 0.000028D; Console.WriteLine(String.Format("{0:F20}", dbltest).TrimEnd('0'));
I use the NeckDimension property in two places and edit the view and the view. Here is how they are displayed.
@Html.TextBoxFor(model => model.NeckDimension, new { style = "width:75px;" }) @Html.DisplayFor(model => model.NeckHDimension)
UPDATE Apparently DisplayFormat will not work with TextBoxFor. I tried changing my @ Html.TextBoxFor to Html.EditorFor and giving it a class, but it failed with the following exception.
The model item passed into the dictionary is of type 'System.Double', but this dictionary requires a model item of type 'System.String'
This old code still works:
@Html.TextBoxFor(model => model.NeckDimension, new { style = "width:75px;" })
This code gave an exception:
@Html.EditorFor(model => model.NeckDimension, new {@class = "formatteddecimal"})
It looks like my options fix it with javascript or fix it with an editor template, but I donβt have time to research and study the second option at this stage.
DECISION:
I created an editor template for double? in the following way.
@model double? @{ var ti = ViewData.TemplateInfo; var displayValue = string.Empty; if (Model.HasValue) { displayValue = String.Format("{0:F20}", @Model.Value).TrimEnd('0'); } <input id="@ti.GetFullHtmlFieldId(string.Empty)" name="@ti.GetFullHtmlFieldName(string.Empty)" type="text" value="@displayValue" /> }