【问题标题】:How do I display a negative currency in red?如何以红色显示负货币?
【发布时间】:2012-07-13 10:31:49
【问题描述】:

我有以下html代码...

<%=String.Format("{0:C0}", item.currency)%>

我需要货币格式,但我的否定显示是这样的......

($2,345)

我希望格式为红色。我可以设置一个切换变量,但有没有更简单的方法?

【问题讨论】:

  • 您是在页面上还是在某些 HTML 控件中显示原始文本?如果item.currency &lt; 0,您可以将样式设置为红色。
  • 好的,所以我必须检查货币并且无法格式化显示负数的方式...
  • 用jQuery你可以做到这一点
  • 根据数字内容更改对象的 CSS 类 - stackoverflow.com/questions/6284408/…

标签: asp.net .net html asp.net-mvc


【解决方案1】:

在我的项目中,我想做同样的事情,但也将负值显示为“-$2345”而不是括号。

为了处理格式,我首先将以下内容添加到我的 BaseController 类(顾名思义,它是我所有控制器的基类):

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);

    System.Globalization.CultureInfo modCulture = new System.Globalization.CultureInfo("en-US");
    modCulture.NumberFormat.CurrencyNegativePattern = 1;
    Thread.CurrentThread.CurrentCulture = modCulture;
}

http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern.aspx。这处理了数字的格式。至于红色,我添加了一个新的css类,叫做“negative”:

.negative
{
    color: Red;
}

然后在我的 .aspx 文件中:

<% if (item.currency < 0.0M)
{ %>
<span class="negative"><%=String.Format("{0:C}", item.currency)%></span>
<% }
else
{ %>
<span><%=String.Format("{0:C}", item.currency)%></span>
<% } %>

将它放在 css 类中的好处是,对于动态站点,如果它稍后变为正数(反之亦然,如果正值变为负数),我可以使用 jQuery 简单地从有问题的 span/div 并将文本设为默认或红色。

【讨论】:

  • BaseController 类指的是什么?
  • @Laggel 我创建了一个 BaseController 类,我的所有其他控制器都从该类派生。这给了我一个放置通用设置代码的地方(就像我上面提到的初始化中的那样)。
猜你喜欢
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多