这是我在 View 模型中的字段:
public decimal MyValue { get; set; }
这是我在 View 中显示值的方式:
@Html.EditorFor(model => model.MyValue)
我从DB一路调试,把JS都关掉了。我仍然在 View 中得到该模型的值为 12.34345,但呈现给用户的最终值为 12.34。
This问题是询问如何解决这个问题,但原因尚不清楚。
有趣的是,当我使用:
@Html.HiddenFor(model => model.MyValue)
四舍五入没有发生。
最佳答案
它是 decimal
的默认 EditorTemplate
的函数。形成source code (注意格式是 "{0:0.00}"
)
internal static string DecimalTemplate(HtmlHelper html)
{
if (html.ViewContext.ViewData.TemplateInfo.FormattedModelValue == html.ViewContext.ViewData.ModelMetadata.Model)
{
html.ViewContext.ViewData.TemplateInfo.FormattedModelValue = String.Format(CultureInfo.CurrentCulture, "{0:0.00}", html.ViewContext.ViewData.ModelMetadata.Model);
}
return StringTemplate(html);
}
如果要显示保存的小数位,请使用 @Html.TextBoxFor(m => m.MyValue)
,或者您可以使用 DisplayFormatAttribute
应用您自己的格式code>,它将被 EditorFor()
方法遵守,例如
[DisplayFormat(DataFormatString = "{0:0.00000}", ApplyFormatInEditMode = true)]`
public decimal MyValue { get; set; }
关于c# - 为什么razor会自动四舍五入到小数点后2位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43447058/