简体   繁体   English

C#数字格式:前导加号AND空格

[英]C# number format: leading plus sign AND spaces

What I'm trying to do is to display numbers in a finance report like this: 我要做的是在财务报告中显示如下数字:

+   5000
+    176
-  10000
- 620230

So I need to print out number that's 6 digits long, with leading sign. 所以我需要打印出6位数的数字,带有前导符号。

I tried to combine leading sign with leading spaces like this: String.Format("{0,7:+#;-#;+0}", value); 我尝试将前导符号与前导空格组合如下: String.Format("{0,7:+#;-#;+0}", value); , but turns out it gives me: ,但事实证明它给了我:

   +5000
    +176
  -10000
 -620230

Is there anyway to use String.Format to get the output I want? 无论如何使用String.Format来获取我想要的输出?

Edit : I understand that I could make my own format function to achieve that result, and I did use one. 编辑 :我知道我可以创建自己的格式函数来实现该结果,并且我确实使用了一个。 I'm asking out of curiosity with String.Format to see if it's could be done. 我用String.Format好奇心,看看是否可以做到。

You need some trick to combine the parts (the sign and the number). 你需要一些技巧来组合部分(符号和数字)。 Here is how it's done: 以下是它的完成方式:

string.Format("{0:+;-;+}{0,7:#;#;0}",someNumber);

{0,7:#;#;0} will format the number so that only the absolute value is displayed. {0,7:#;#;0}将格式化数字,以便仅显示绝对值。 While the first part {0:+;-;+} will just display the sign accordingly to the value. 而第一部分{0:+;-;+}将仅根据值显示符号。 You can make your own method to wrap that line of code as for convenience. 为方便起见,您可以创建自己的方法来包装该行代码。

Here is a method that returns a formatted string. 这是一个返回格式化字符串的方法。 It's quite self explanatory. 这是非常自我解释的。

static string FormatFinancialNumber(int number) {
    string sign = number < 0 ? "-" : "+"; // decide the sign
    return sign + Math.Abs(number).ToString().PadLeft(7); // Make the number part 7 characters long
}

Usage: 用法:

Console.WriteLine(FormatFinancialNumber(1));
Console.WriteLine(FormatFinancialNumber(-12));
Console.WriteLine(FormatFinancialNumber(123));
Console.WriteLine(FormatFinancialNumber(-1234));
Console.WriteLine(FormatFinancialNumber(12345));

Output: 输出:

+      1
-     12
+    123
-   1234
+  12345

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

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