Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Conditional formatting for positive, negative, and zero numbers

0.00/5 (No votes)
3 Sep 2013 1  
This is a useful tip for formatting numbers in C#.

Introduction  

We often want to format a number using format strings, but we face a problem of deciding the format according to the sign of the number (+ve, -ve or zero). This is an easy tip for formatting numbers.

Using the code 

Notice the semi-colon in the formatting string, it's used as a separator between different formatting, first part is for positive number formatting, second is for negative number, and the last is for zero formatting.  

string formatstring = "+ 0.##; - 0.##; This is zero";
 
var no1 = 192.15;
var no2 = - 192.15;
var no3 = 0;
 
Console.WriteLine(no1.ToString(formatstring));
Console.WriteLine(no2.ToString(formatstring));
Console.WriteLine(no3.ToString(formatstring));
 
Console.Read();

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here