Search code examples
c#.netformattingstring-formatting

Custom numeric format string to always display the sign


Is there any way I can specify a standard or custom numeric format string to always output the sign, be it +ve or -ve (although what it should do for zero, I'm not sure!)


Solution

  • Yes, you can. There is conditional formatting. See Conditional formatting in MSDN

    eg:

    string MyString = number.ToString("+0;-#");
    

    Where each section separated by a semicolon represents positive and negative numbers

    or:

    string MyString = number.ToString("+#;-#;0");
    

    if you don't want the zero to have a plus sign.