如何以红色显示负货币?

时间:2012-07-13 14:42:53

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

我有以下HTML代码......

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

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

($2,345)

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

1 个答案:

答案 0 :(得分: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。这照顾了数字的格式。至于红色,我添加了一个名为“negative”的新css类:

.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并使文本默认或为红色。

相关问题