【问题标题】:How to add currency symbol without rounding value on asp.net page如何在 asp.net 页面上添加货币符号而不进行舍入值
【发布时间】:2019-06-26 10:54:10
【问题描述】:

我有十进制类型的 DiscountTotal 变量。值是在页面后面的代码上设置的,在页面加载后,值会被四舍五入。

<%#DataBinder.Eval(Container.DataItem, "DiscountTotal","{0:C}")%>

价值 7610.3250D 显示为 £7610.33。我喜欢根据登录用户显示为 7610.32 英镑或 7610.32 美元。当前的文化设置已经存在,我只担心四舍五入。

【问题讨论】:

标签: c# asp.net .net gridview


【解决方案1】:

尝试使用 MidpointRounding 进行舍入

decimal value = 7610.3250m;
string formattedValue = string.Format("{0:C}", decimal.Round(value, 2, MidpointRounding.ToEven));

【讨论】:

    【解决方案2】:

    假设您的DiscountTotal 属性的下划线数据类型是System.Decimal,您可以使用它来为ToString 方法提供适当的文化,因此它可以根据指定的文化呈现货币符号。

    // For $, use en-US instead of en-GB.
    // You must make this available in your session.
    var sessionUiCulture = new System.Globalization.CultureInfo("en-GB");
    ...
    ...
    <%# decimal.Round((decimal)DataBinder.Eval(Container.DataItem, "DiscountTotal"), 2, MidpointRounding.ToEven).ToString("C", sessionUiCulture) %>
    

    此外,如果您在整个应用程序中需要这种行为,实现此目的的最佳方法是将属性 System.Globalization.CultureInfo.CurrentUICulture 设置为请求管道中的适当文化,这样您就不必担心这一点。

    根据你走的路线,你应该考虑为此创建一个扩展方法:

    public static string ToCurrency(this decimal value)
    {
        return decimal.Round(value, 2, MidpointRounding.ToEven).ToString("C");
    }
    

    所以你可以这样做:

    <%# ((decimal)DataBinder.Eval(Container.DataItem, "DiscountTotal")).ToCurrency() %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 2017-12-10
      • 1970-01-01
      相关资源
      最近更新 更多