65.9K
CodeProject is changing. Read more.
Home

Conditional formatting for positive, negative, and zero numbers

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2 votes)

Sep 3, 2013

CPOL
viewsIcon

11626

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();