Formatting Negative Numbers Differently Than Positive

Environment: .NET

In my last article, I presented formatting specifiers for dates and times. Format specifiers are most often used with numbers. For example, to print a decimal number to three levels of precision, you would use D3 as the specifer. The following uses this specifier within WriteLine:

System.Console.WriteLine("A Number: {0:D3}", dVar);

While numeric specifiers work with both positive and negative numbers, there are times when you want a negative number treated differently than a positive number.

The placeholder for specifying the format of a value can actually be separated into either two or three sections. If the placeholder is separated into two sections, the first is for positive numbers and zero and the second is for negative numbers. If it is broken into three sections, the first is for positive values, the middle is for negative values, and the third is for zero.

The placeholder is broken into these sections using a semicolon. The placeholder number is then included in each. For example, to format a number to print with three levels of precision when positive, five levels when negative, and no levels when zero, you do the following:

{0:D3;D5;'0'}

Listing 1 presents this example in action along with a couple of additional examples.

Listing 1 — threeway.cs.

 1: // threeway.cs - Controlling the formatting of numbers
 2: //----------------------------------------------------
 3: 
 4: using System;
 5: 
 6: class myApp
 7: {
 8:  public static void Main()
 9:  {
10:    Console.WriteLine("\nExample 1...");
11:    for ( int x = -100; x <= 100; x += 100 )
12:    {
13:      Console.WriteLine("{0:000;-00000;'0'}", x);
14:    }
15: 
16:    Console.WriteLine("\nExample 2...");
17:    for ( int x = -100; x <= 100; x += 100 )
18:    {
19:      Console.WriteLine("{0:Pos: 0;Neg: -0;Zero}", x);
20:    }
21: 
22:    Console.WriteLine("\nExample 3...");
23:    for ( int x = -100; x <= 100; x += 100 )
24:    {
25:      Console.WriteLine("{0:You Win!;You Lose!;You Broke
                               Even!}", x);
26:    }
27:  }
28: }

This listing produces the following output:

Example 1...
-00100
0
100

Example 2...
Neg: -100
Zero
Pos: 100

Example 3...
You Lose!
You Broke Even!
You Win!

This listing helps illustrate how to break the custom formatting into three pieces. A for loop is used to create a negative number, increment the number to zero, and finally increment it to a positive number. The result is that the same WriteLine can be used to display all three values. This is done three separate times for three different examples.

In line 13, you see that the positive value will be printed to at least three digits because there are three zeros in the first formatting position. The negative number will include a negative sign followed by at least 5 numbers. You know this because the dash is included in the format for the negative sign, and there are five zeros. If the value is equal to zero, a zero will be printed.

In the second example, text is included with the formatting of the numbers. This is also done in the third example. The difference is that in the second example, zero placeholders are also included so the actual numbers will print. This is not the case with the third example where only text is displayed.

As you can see by all three of these examples, it is easy to cause different formats to be used based on the sign (positive or negative) of a variable.

For More Information...

Check out my previous article on formatting dates and times. Additionally, you can get more information from my book, Sams Teach Yourself C# in 21 Days.



About the Author

Bradley Jones

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page

Comments

  • Interesting Article

    Posted by Brad Jones on 02/23/2004 11:26am

    This is a style of formatting that is not used very often.

    Reply
  • http://www.codeguru.com/net_general/NETFormat2.html

    Posted by Legacy on 03/22/2003 12:00am

    Originally posted by: Ernie

    A link to the previous article would be nice.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • You may already know about some of the benefits of Bluemix, IBM's open platform for developing and deploying mobile and web applications. Check out this webcast that focuses on building an Android application using the MobileData service, with a walk-through of the real process and workflow used to build and link the MobileData service within your application. Join IBM's subject matter experts as they show you the way to build a base application that will jumpstart you into building your own more complex app …

  • A modern mobile IT strategy is no longer an option, it is an absolute business necessity. Today's most productive employees are not tied to a desk, an office, or a location. They are mobile. And your company's IT strategy has to be ready to support them with easy, reliable, 24/7 access to the business information they need, from anywhere in the world, across a broad range of communication devices. Here's how some of the nation's most progressive corporations are meeting the many needs of their mobile workers …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds