Formatting for positive, negative, and zero numbers

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.

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.

class Program
static string formatstring = “+ 0.##; – 0.##; This is zero”;
static void Main(string[] args)
var no1 = 1;
var no2 = -192.15;
var no3 = 0;

Console.WriteLine(no1.ToString(formatstring)); //Result: +1
Console.WriteLine(no2.ToString(formatstring)); //Result: -192.15
Console.WriteLine(no3.ToString(formatstring)); //Result: This is zero


By Sriramjithendra Posted in C#.NET

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s