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

标签 c# asp.net-mvc razor decimal rounding

这是我在 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/

相关文章:

c# - 在 treeView 中取消选择

c# - 如何使用 C# 编辑二进制文件的十六进制值

c# - 隐藏来自 ASP.NET MVC 中操作的路由值?

c# - 重定向到页面但特定选项卡

c# - 将 Razor View 渲染为字符串会导致额外的格式标记(制表符、换行符)?如何去除?

c# - ServicePointManager.DefaultConnectionLimit 返回 Int32.MaxValue

c# - 是否可以统一序列化 Sprite ?

asp.net-mvc - 为什么 Response.Redirect 与 new RedirectResult() 之间存在差异?

c# - 调用ajax mvc4 c#的绝对路径

c# - 如何从 MVC 中的部分页面设置页面标题