Search code examples
c#number-formatting

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.


Solution

  • 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.