Click here to Skip to main content
15,898,689 members
Articles / Programming Languages / C#
Tip/Trick

Conditional formatting for positive, negative, and zero numbers

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
3 Sep 2013CPOL 11.4K   2   2
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.  

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader IT WORX
Egypt Egypt
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUseful Pin
moh moh oo3-Sep-13 23:29
professionalmoh moh oo3-Sep-13 23:29 
GeneralRe: Useful Pin
Ahmed_Mostafa4-Sep-13 0:47
professionalAhmed_Mostafa4-Sep-13 0:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.