为什么razor会自动四舍五入到小数点后2位?

Why razor is rounding to a decimal type to 2 decimal places automatically?

这是我的视图模型中的字段:

public decimal MyValue { get; set; }

以下是我在视图中显示值的方式:

@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 应用您自己的格式,EditorFor() 方法将遵守该格式, 例如

[DisplayFormat(DataFormatString = "{0:0.00000}", ApplyFormatInEditMode = true)]`
public decimal MyValue { get; set; }

请看下面的源码 https://github.com/aspnet/Mvc/blob/6436538068d19c475d5f7c9ce3d0080d2314f69d/src/Microsoft.AspNetCore.Mvc.ViewFeatures/Internal/DefaultEditorTemplates.cs

见下面的方法

public static IHtmlContent DecimalTemplate(IHtmlHelper htmlHelper)
{
        if (htmlHelper.ViewData.TemplateInfo.FormattedModelValue == htmlHelper.ViewData.Model)
        {
            htmlHelper.ViewData.TemplateInfo.FormattedModelValue =
                string.Format(CultureInfo.CurrentCulture, "{0:0.00}", htmlHelper.ViewData.Model);
        }

        return StringTemplate(htmlHelper);
}