【问题标题】:Currency format issue in ASP.NET COREASP.NET CORE 中的货币格式问题
【发布时间】:2017-06-14 20:13:08
【问题描述】:

在我的ASP.NET Core 1.1EF Core 1.1 中,跟随View 显示Cost 值,没有美元格式。我想将其显示为$1,945.25问题:我可能缺少什么? 注意:我尝试了thisthis SO Posts,但仍然是同样的问题。

型号

public class costs
{
....
....        
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public float? Costs { get; set; }
....
....
}

TestViewModel

public class TestViewModel
{
....
....  
public string ProdName{ get; set; }   
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public float? Costs { get; set; }
....
....
}

查看

@model myProj.Models.TestVewModel
....
....
<td>@Html.DisplayFor(t =>t.Cost)</td>

<td>@Html.EditorFor(t =>t.Cost)</td>
....
....

更新

我能想到的this post 和this 之间的唯一区别可能是我使用的SQL Server 2012 的数据类型为real 用于costs 列。但是,我不确定这是否是问题的原因。 real 数据类型是通过 EF-Core migration 命令创建的。

【问题讨论】:

  • 好吧,对于初学者来说,不要使用float 作为货币。使用decimal。如果不使用近似逻辑,就无法准确表示像 .1 这样简单的东西。但是,这不是你的问题。我不完全确定你的问题是什么..只是它的格式不正确,即使使用 DisplayFormat 属性和 DisplayFor/EditorFor?查看您的代码,您将 Attribute 放在 costs 对象上,但您在视图中使用了 TestVewModel。我知道你说TestViewModel 是“和上面一样”,但真的吗?为什么不给我们一个可验证的小样本。
  • 仅供参考,请参阅dotnetfiddle.net/2cGikc - 这表明值的格式正确。所以很明显,你正在做一些你没有向我们展示的事情,这正在破坏它。
  • @ErikFunkenbusch 该问题仅与数据显示格式不正确有关。这些值显示正确,但就像1945.25 这样的数字而不是$1,945.25 我也尝试过DisplayFormat 属性和DisplayFor/EditorFor。如果有帮助,我刚刚添加了TestViewModel 代码和一个 UPDATE 部分。另外,将float 更改为decimal 是否会对实际值产生影响?
  • 正如我所说,浮点数不是你的问题,但你真的不想使用浮点数作为货币,因为浮点数舍入错误。正如您在我链接到的 dotnetfiddle 中看到的那样,使用该属性进行格式化就可以了。它与 sql server 类型无关。

标签: asp.net-mvc visual-studio-2015 asp.net-core asp.net-core-mvc


【解决方案1】:

如果没有任何效果,您可以选择以下方法之一:

<td>$@t.Cost</td>

<td>@string.Format("{0:C}", t.Cost)</td>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多