【发布时间】:2012-07-28 06:31:08
【问题描述】:
在我的项目中有很多地方我尝试使用内置的{0:C} 货币格式显示货币。如果该数字为负数,则将其包围在括号中的值。我希望它改用负号。
我的 web.config 将文化设置为 auto,它解析为 en-US。
理想的解决方案是一些全局 web.config 或其他设置,使 {0:C} 显示 en-US 文化的负号,但我也愿意接受其他不太出色的解决方案。
【问题讨论】:
在我的项目中有很多地方我尝试使用内置的{0:C} 货币格式显示货币。如果该数字为负数,则将其包围在括号中的值。我希望它改用负号。
我的 web.config 将文化设置为 auto,它解析为 en-US。
理想的解决方案是一些全局 web.config 或其他设置,使 {0:C} 显示 en-US 文化的负号,但我也愿意接受其他不太出色的解决方案。
【问题讨论】:
您必须指定正确的NumberFormatInfo.CurrencyNegativePattern,它可能是 1。
Decimal dec = new Decimal(-1234.4321);
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
culture.NumberFormat.CurrencyNegativePattern = 1;
String str = String.Format(culture, "{0:C}", dec);
Console.Write(str);
输出:
-$1,234.43
【讨论】:
我认为这里的答案组合会让你更接近你想要的。
protected void Application_BeginRequest()
{
var ci = CultureInfo.GetCultureInfo("en-US");
if (Thread.CurrentThread.CurrentCulture.DisplayName == ci.DisplayName)
{
ci = CultureInfo.CreateSpecificCulture("en-US");
ci.NumberFormat.CurrencyNegativePattern = 1;
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
}
如果您不想编写任何代码来处理这样的单一文化...我相信您需要建立自己的文化...Check this Question
【讨论】:
据我了解你的问题。
您希望根据文化显示货币格式。
每次你做特定文化的事情时,.NET 都会查看Thread.CurrentThread.CurrentCulture 和Thread.CurrentThread.CurrentUICulture。
您可以在 ASP.NET 中的 global.asax BeginRequest 方法中设置所需的文化。
protected void Application_BeginRequest()
{
var ci = CultureInfo.GetCultureInfo("en-US"); // put the culture you want in here
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
【讨论】: