Three Part Conditional Numeric Format Strings (for Positive, Negative, and Zero Numbers)

When we’re formatting numbers we can use a format string that allows us to specify a different format to be used whenever the number is positive, negative or zero.

To do this we separate the 3 parts by a semicolon.

For example the format string "(+)#.##;(-)#.##;(sorry nothing at all)" will output:

  • (+)99.99 if the value was 99.99
  • (-)23.55 if the value was -23.55
  • (sorry nothing at all) if the value was zero

You can also use a two part conditional format string where the first part will be used if the number is positive or zero; the second part will be used if the number is negative.

Check out the MSDN page for more info…

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.


Add comment