.netcore asp-for decimal 丢失小数位
.netcore asp-for decimal loses decimal places
我 运行 遇到一个问题,在我看来,在使用 asp-for 标签助手时我丢失了小数位。它似乎总是四舍五入到 2 位小数,而我想让它四舍五入到 3 位小数(在这种情况下)。
我可以在调试器中看到模型中的值有 3 个小数位,如 e
但在我看来,它显示为 1.28
而不是 1.275
:
这是我的表单视图,如您所见,实际上并没有发生什么特别的事情(asp-has-error
标签助手是该项目的自定义标签助手):
<div class="form-group row">
<label asp-for="RatePercentage" class="col-lg-4 col-form-label"></label>
<div class="col-lg-8">
<input asp-for="RatePercentage" asp-has-error="@Html.HasErrorFor(m => m.RatePercentage)" class="form-control"/>
</div>
</div>
关于如何让小数点后 3 位显示在此处的任何想法?
这只是默认设置。您可以使用 DisplayFormat
属性使其随心所欲:
[DisplayFormat(DataFormatString = "{0:[format]}", ApplyFormatInEditMode = true)]
public decimal RatePercentage { get; set; }
其中 [format]
是您想要的格式字符串。参见 Standard Numeric Format Strings and Custom Numeric Format Strings。
另一种阻止标签助手应用此默认格式的方法是显式指定 input
元素的 type
属性并将其分配为 text
,如下所示:
<input type="text" asp-for="RatePercentage" …/>
然后您在输入控件中得到 'raw' 十进制值,您可以使用编辑掩码或以其他方式自行设置格式,而不会自动丢失否则会发生的值的精度。
我 运行 遇到一个问题,在我看来,在使用 asp-for 标签助手时我丢失了小数位。它似乎总是四舍五入到 2 位小数,而我想让它四舍五入到 3 位小数(在这种情况下)。
我可以在调试器中看到模型中的值有 3 个小数位,如 e
但在我看来,它显示为 1.28
而不是 1.275
:
这是我的表单视图,如您所见,实际上并没有发生什么特别的事情(asp-has-error
标签助手是该项目的自定义标签助手):
<div class="form-group row">
<label asp-for="RatePercentage" class="col-lg-4 col-form-label"></label>
<div class="col-lg-8">
<input asp-for="RatePercentage" asp-has-error="@Html.HasErrorFor(m => m.RatePercentage)" class="form-control"/>
</div>
</div>
关于如何让小数点后 3 位显示在此处的任何想法?
这只是默认设置。您可以使用 DisplayFormat
属性使其随心所欲:
[DisplayFormat(DataFormatString = "{0:[format]}", ApplyFormatInEditMode = true)]
public decimal RatePercentage { get; set; }
其中 [format]
是您想要的格式字符串。参见 Standard Numeric Format Strings and Custom Numeric Format Strings。
另一种阻止标签助手应用此默认格式的方法是显式指定 input
元素的 type
属性并将其分配为 text
,如下所示:
<input type="text" asp-for="RatePercentage" …/>
然后您在输入控件中得到 'raw' 十进制值,您可以使用编辑掩码或以其他方式自行设置格式,而不会自动丢失否则会发生的值的精度。