最近项目对于数字精确度的要求较高,因此使用Decimal作为属性型态来避免计算上的误差。就在要将数值呈现于画面上时,突然发现数值不大正确,原本小数位数有四位(1.1234),而呈现在画面上却只剩下2位小数(1.12),着实让我心惊胆跳一下。
事由探讨
当使用@Htme.EditorFor来处理Decimal型态数据时,会自动对应到内建的Decimal Editor Template样板中;再仔细研究一下Source Code会发现,原来DecimalTemplate会自动地帮我们把数据转换为2位小数的数字,难怪不管小数几位的数值都会变成2位小数的数值。
解决方案
方法1 直接在属性上加注 DisplayFormat Attribute 来控制显示格式
ViewModel
{
public double DoubleNumber { get; set; }
// 加注 DisplayFormat 避免被 Decimal Template 转为小数2位格式
[DisplayFormat(DataFormatString = "{0}", ApplyFormatInEditMode = true)]
public decimal DecimalNumber { get; set; }
}
方法2 使用@Html.TextBoxFor取代@Html.EditorFor功能
View
@Html.LabelFor(model => model.DoubleNumber, htmlAttributes = new { @class = "control-label col-md-2" } })
@Html.EditorFor(model => model.DoubleNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.LabelFor(model => model.DecimalNumber, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.TextBoxFor(model => model.DecimalNumber, htmlAttributes: new { @class = "form-control" }) @*@Html.EditorFor(model => model.DecimalNumber, new { htmlAttributes = new { @class = "form-control" } })*@
注意:本文归作者所有,未经作者允许,不得转载