简体   繁体   English

如何格式化签名货币

[英]How to format signed currency

I have the following scenario. 我有以下场景。 A decimal value needs to be displayed as a currency but include the appropriate currency symbol and sign, thus: 小数值需要显示为货币,但包含相应的货币符号和符号,因此:

  1. -45.23 is displayed as -£45.23 -45.23显示为 - £45.23
  2. 45.23 is displayed as +£45.23 45.23显示为+£45.23

The currency sign must come from System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol . 货币符号必须来自System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol I have this, but I can't find a way to swap the sign and currency symbol: 我有这个,但我找不到交换标志和货币符号的方法:

string s1 = string.Format(@"{1}{0:+#,##0.00;-#,##0.00}", 45.09M, 
    System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol);
Console.WriteLine(s2);
string s2 = string.Format(@"{1}{0:+#,##0.00;-#,##0.00}", -45.09M, 
    System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol);
Console.WriteLine(s2);

Outputs: 输出:

£+45.09
£-45.09

I want: 我想要:

+£45.09
-£45.09

UPDATE UPDATE

Someone posted another answer regarding the NumberFormatInfo.CurrencyPositivePattern Property, which looked promising, especially since the but it appears that Microsoft overlooked the possibility that the NumberFormatInfo.CurrencyNegativePattern Property contains various options for the presentation of the negative sign. 有人发布了另一个关于NumberFormatInfo.CurrencyPositivePattern属性的答案,这看起来很有希望,特别是因为看起来微软忽略了NumberFormatInfo.CurrencyNegativePattern属性包含各种负号表示选项的可能性。 However, the NumberFormatInfo.CurrencyPositivePattern does not include an option to include the positive sign! 但是, NumberFormatInfo.CurrencyPositivePattern不包含包含正号的选项! Damn. 该死的。 Thanks to whoever it was that mentioned it, but deleted their comments. 感谢无论是谁提到它,但删除了他们的评论。 I learnt someone nevertheless. 不过我还是学到了一些人。

As I posted this, I realised the answer is to do this in three steps instead of two: 正如我发布的那样,我意识到答案是分三步而不是两步:

string s1 = string.Format(@"{0:+;-}{1}{0:#,##0.00;#,##0.00}", 45.09M, System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol);
Console.WriteLine(s1);

string s2 = string.Format(@"{0:+;-}{1}{0:#,##0.00;#,##0.00}", -45.09M, System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol);
Console.WriteLine(s2);

Outputs: 输出:

+£45.09
-£45.09

Your string.Format is explicitly putting the +/- at the front. 你的string.Format 明确地将+/-放在前面。

If you split the operation into two steps, it becomes easier. 如果将操作分为两个步骤,则会变得更容易。 First inject your currentcy symbol, then format your number. 首先注入你的当前符号,然后格式化你的号码。

string fmt = string.Format(@"{{0:+{0}#,##0.00;-{0}#,##0.00}}",  
    System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol);
string s1 = string.Format(fmt, 45.09M);
Console.WriteLine(s1); 
string s2 = string.Format(fmt, -45.09M);
Console.WriteLine(s2); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM