【问题标题】:.netcore asp-for decimal loses decimal places.net core asp-for decimal 丢失小数位
【发布时间】:2020-07-15 21:51:58
【问题描述】:

我遇到了一个问题,在我看来,使用 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 位吗?

【问题讨论】:

  • RatePercentage 模型属性上是否有任何属性?
  • 无属性号。

标签: asp.net-core asp.net-core-tag-helpers


【解决方案1】:

这只是默认设置。你可以使用DisplayFormat 属性来做任何你喜欢的:

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

其中[format] 是您想要的格式字符串。请参阅Standard Numeric Format StringsCustom Numeric Format Strings

【讨论】:

  • 如果有人不想点击上面带有所有格式选项的有用链接,则显示三位小数的格式是:[DisplayFormat(DataFormatString = "{0:N3}", ApplyFormatInEditMode = true )]
【解决方案2】:

阻止标记助手应用此默认格式的另一种方法是显式指定input 元素的type 属性并将其分配为text,如下所示:

<input type="text" asp-for="RatePercentage" …/>

然后您在输入控件中获得“原始”十进制值,您可以使用编辑掩码或以其他方式自行格式化,而不会自动失去否则会发生的值的精度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2021-07-31
    相关资源
    最近更新 更多