简体   繁体   中英

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.

I tried to combine leading sign with leading spaces like this: 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?

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.

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. While the first part {0:+;-;+} will just display the sign accordingly to the value. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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