c# - 如何使用 NumberFormatInfo 删除负值的括号

标签 c# .net globalization iformatprovider

我们目前正在使用以下内容在我们的网络应用程序中创建美元值(value):

string.Format("{0:C0}", dollarValue );

在这个例子中,如果 dollarValue 是 145,那么我们会看到:145 美元。如果它是 -145,那么我们将看到 ($145) 而不是 -$145。请注意,对于我们来说,dollarValue 是一个 double 值,但它可以是任何数字类型。我想。

无论如何,我想要的是 145 美元或 -145 美元。

现在,根据我的研究,使用 NumberFormatInfo 类可以做到这一点。我不知道如何使用它,也找不到任何有效的例子。我确实在这里看到了这个问题:C# creating a custom NumberFormatInfo to display "Free" when a currency value is $0.00但是从 MSDN 链接到这个问题的例子似乎与我真正想做的有点不同。

我意识到,我需要执行以下操作:

double dollarValue = -145d;
string myMoney = dollarValue.ToString( "C0", someIFormatProvider );

其中 someIFormatProvider 可能是 NumberFormatInfo 类型。现在,我所做的是:

NumberFormatInfo ni = new NumberformatInfo();
ni.CurrencyNegativePattern = 1; // The value 1 should mean not to use parenthesis
string myMoney = dollarValue.ToString( "C0", ni );

...我得到一个“实例是只读的”异常。虽然 CurrencyNegativePattern 属性的“文档”说您可以设置和获取值,但显然您不能。此外, NumberFormatInfo 是一个密封类。我不能轻易地基于它创建一个新类并覆盖该值。

我不知道如何处理这个问题。现在,我的解决方法是只否定我的负值并得到一个积极的结果,我再次执行 string.Format(...) 。是的,我知道前面没有负号,但是,当然,根据需要在结果前面添加一个“-”很容易解决这个问题。

有人能为我提供一个工作示例,说明如何在这种情况下正确有效地使用 NumbefFormatInfo 类吗?谢谢。

最佳答案

您可以复制 CurrentCulture 中的 NumberFormat 属性(这将确保您在全局化应用程序时保持正确的货币符号)。之后,只需设置 CurrencyNegativePattern属性设置为所需的值,并在 double.ToString() 函数中传入您的 NumberFormatInfo,如下所示:

NumberFormatInfo noParens = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
noParens.CurrencyNegativePattern = 1;
double dollarValue = -145d;
string output = dollarValue.ToString("C0", noParens); // outputs -$145

关于c# - 如何使用 NumberFormatInfo 删除负值的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11014878/

相关文章:

asp.net - Page.UICulture -- 如何检索两个字母的 UICulture 代码?

c# - LINQ - 以列名作为字符串参数访问列

c# - 在代码隐藏中将字符串转换为可执行的 C# 代码

c# - 单击按钮时显示新表单

asp.net-mvc - DateTime 和 ASP.NET MVC 3 模型绑定(bind)的全局化问题

c# - 用千位分隔符解析小数

c# - 某些方法的 WCF REST 基本身份验证

c# - 对测试失败+异常进行截图

c# - SetSystemTime - UTC 或本地时间?

.net - 针对锁定的文件测试您的代码?