Search code examples
c#integertostring

How to format integer value as string with symbol "+" if its positive in C#?


I want to print values as "+ 10 %" and "- 10 %".

For percentage I use myValue.ToString("P0") and its output is: 10 %, - 10 %.

How to add "+" symbol to that?

Thanks a lot


Solution

  • The options available are at https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#PFormatString

    There is a NegativeSign option to change the negative symbol, but not the positive one, so in that case you will have to fall back to having your own conditional code to use the P0 format, or multiply your value by 100 and use a conditional format specifier as described in the answer linked in the comments, Custom numeric format string to always display the sign .