Home

Formatting Data Display

 

Introduction

Instead of using two Write() or a combination of Write() and WriteLine() to display data, you can convert a value to a string and display it. To do this, you can provide two strings to Write() or WriteLine() and separate them with a comma:

  1. The first part of the string provided to Write() or WriteLine() is the complete string that will display to the user. This first string itself can be made of different sections:
    1. One section is a string in any way you want it to display
    2. Another section is a number included between an opening curly bracket "{" and a closing curly bracket "}". This combination of "{" and "}" is referred to as a placeholder

      You can put the placeholder anywhere inside of the string. The first placeholder must have number 0. The second must have number 1, etc. With this technique, you can create the string anyway you like and use the placeholders anywhere inside of the string
  2. The second part of the string provided to Write() or WriteLine() is the value that you want to display. It can be one value if you used only one placeholder with 0 in the first string. If you used different placeholders, you can then provide a different value for each one of them in this second part, separating the values with a comma

Here are examples:

using namespace System;

int main()
{
    String ^ FullName = L"Anselme Bogos";
    int Age = 15;
    double HSalary = 22.74;

    Console::WriteLine(L"Full Name: {0}", FullName);
    Console::WriteLine(L"Age: {0}", Age);
    Console::WriteLine(L"Distance: {0}", HSalary);

    return 0;
}

This would produce:

Full Name: Anselme Bogos
Age: 15
Distance: 22.74

As mentioned already, the numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. The syntax used is:

Write("To Display {0} {1} {2}", First, Second, Third);

You can use the sections between a closing curly bracket and an opening curly bracket to create a meaningful sentence.

Conversion To String

We mentioned earlier that everything the user types using the keyboard is primarily a string and it's your job to convert it to the appropriate type. In reverse, if you have a value that is not a string, you can easily convert it to a string. To support this, each .NET Framework data type provides a mechanism called ToString.

To conversion a value of a primitive data type to a string, type the name of the variable, followed by a period, followed by ToString(). Here is an example:

using namespace System;

int main()
{
    String ^ FullName = L"Anselme Bogos";
    int Age = 15;
    double HSalary = 22.74;

    Console::WriteLine(L"Full Name: {0}", FullName);
    Console::WriteLine(L"Age: {0}", Age.ToString());
    Console::WriteLine(L"Distance: {0}", HSalary.ToString());

    return 0;
}

In some cases, you will type something in the parentheses of ToString().

Number Formatting

To properly display data in a friendly and most familiar way, you can format it. Formatting tells the compiler what kind of data you are using and how you want the compiler to display it to the user. You can display a natural number in a common value or, depending on the circumstance, you may prefer to show it as a hexadecimal value. When it comes to double-precision numbers, you may want to display a distance with three values on the right side of the decimal separator and in some cases, you may want to display a salary with only 2 decimal places.

The System namespace provides a specific letter that you can use in the Write() or WriteLine()'s placeholder for each category of data to display. To format a value, in the placeholder of the variable or value, after the number, type a colon and one of the appropriate letters from the following table. If you are using ToString(), then, in the parentheses of ToString(), you can include a specific letter or combination inside of double-quotes. The letters and their meanings are:

  Character Used For
  c C Currency values
  d D Decimal numbers
  e E Scientific numeric display such as 1.45e5
  f F Fixed decimal numbers
  g G General and most common type of numbers
  n N Natural numbers
  r R Roundtrip formatting
  x X Hexadecimal formatting
  p P Percentages

Here are examples:

using namespace System;

int main()
{
    double Distance = 248.38782;
    int Age = 15;
    int NewColor = 3478;
    double HSalary = 22.74, HoursWorked = 35.5018473;
    double WeeklySalary = HSalary * HoursWorked;

    Console::WriteLine(L"Distance: {0}", Distance.ToString(L"E"));
    Console::WriteLine(L"Age: {0}", Age.ToString());
    Console::WriteLine(L"Color: {0}", NewColor.ToString(L"X"));
    Console::WriteLine(L"Weekly Salary: {0} for {1} hours",
                 WeeklySalary.ToString(L"c"), HoursWorked.ToString(L"F"));

    return 0;
}

This would produce:

Distance: 2.483878E+002
Age: 15
Color: D96
Weekly Salary: $807.31 for 35.50 hours

As you may have noticed, if you leave the parentheses of ToString() empty, the compiler would use a default formatting to display the value.

As opposed to calling ToString(), you can use the above letters in the curly brackets of the first part of Write() or WriteLine(). In this case, after the number in the curly brackets, type the colon operator followed by the letter.

Line Formatting

In the above programs, to display a line of text, we used Write() or WriteLine(). To position text of different lengths one above the other, we had to "corrupt" a string by including extra-empty spaces. Such a technique is uncertain and less professional. Fortunately, you can format how a string or a line of text should display. There are mechanisms to control the amount of space used to display a string of text and how to align that string on its line.

To specify the amount of space used to display a string, you can use its placeholder in Write() or WriteLine(). To do this, in the placeholder, type the 0 or the incrementing number of the placeholder and its formatting character if necessary and if any. Then, type a comma followed by the number of characters equivalent to the desired width. Here are examples:

using namespace System;

int main()
{
    double Distance = 248.38782;
    int Age = 15;
    int NewColor = 3478;
    double HSalary = 22.74, HoursWorked = 35.5018473;
    double WeeklySalary = HSalary * HoursWorked;

    Console::WriteLine(L"Distance: {0:20}", Distance.ToString(L"E"));
    Console::WriteLine(L"Age: {0,14}", Age.ToString());
    Console::WriteLine(L"Color: {0}", NewColor.ToString(L"X"));
    Console::WriteLine(L"Weekly Salary: {0:C,8}", WeeklySalary.ToString(L"c"));
 
    return 0;
}

This would produce:

Distance: 2.483878E+002
Age:             15
Color: D96
Weekly Salary: $807.31
Press any key to continue . . .

The sign you provide for the width is very important. If it is positive, the line of text is aligned to the right. This should be your preferred alignment for numeric values. If the number is negative, then the text is aligned to the left.

Practical LearningPractical Learning: Formatting Data

  1. To format the values displayed by the application, change the contents of the Exercise.cpp file as follows:
     
    #include <iostream>
    #include "SingleFamily.h"
    
    using namespace std;
    using namespace RealEstate;
    
    int main()
    {
        String ^ strTitle1 = L"=//= Altair Realty =//=";
        String ^ strTitle2 = L"-=- Properties Inventory -=-";
        CSingleFamily ^ home = gcnew CSingleFamily;    
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
       Console::WriteLine("To create a listing, enter the following information");
        Console::Write("Property #:    ");
        home->PropertyNumber = long::Parse(Console::ReadLine());
        Console::WriteLine("Property Condition");
        Console::WriteLine("0. Unknown");
        Console::WriteLine("1. Excellent");
        Console::WriteLine("2. Good (may need minor repair");
        Console::WriteLine("3. Acceptable (needs major repair)");
        Console::WriteLine("4. Even (land is more important)");
        Console::Write("Your Choice:    ");
        home->Condition = int::Parse(Console::ReadLine());
        Console::Write("Street Address: ");
        home->Address = Console::ReadLine();
        Console::Write("City:           ");
        home->City = Console::ReadLine();
        Console::Write("State:          ");
        home->State = Console::ReadLine();
        Console::Write("ZIP Code:       ");
        home->ZIPCode = Console::ReadLine();
        Console::Write("Bedrooms:       ");
        home->Bedrooms = int::Parse(Console::ReadLine());
        Console::Write("Bathrooms:      ");
        home->Bathrooms = float::Parse(Console::ReadLine());
        Console::Write("Stories:        ");
        home->Stories = int::Parse(Console::ReadLine());
        Console::Write("Year Built:     ");
        home->YearBuilt = int::Parse(Console::ReadLine());
        Console::WriteLine("Style");
        Console::WriteLine("U. Unknown");
        Console::WriteLine("S. Split Level");
        Console::WriteLine("C. Colonial");
        Console::WriteLine("G. Georgial");
        Console::Write("Your Choice:    ");
        home->Style = __wchar_t::Parse(Console::ReadLine());
        Console::Write("Garage Spaces:  ");
        home->NumberOfGarageSpaces = int::Parse(Console::ReadLine());
        Console::Write("Total Lot Size: ");
        home->LotSizeInSqFt = double::Parse(Console::ReadLine());
        Console::Write("Market Value:   ");
        home->MarketValue = double::Parse(Console::ReadLine());
      
        system("cls");
    
        Console::WriteLine(strTitle1);
        Console::WriteLine(strTitle2);
        Console::WriteLine("=//= Property Listing =//=");
        Console::WriteLine("Property #:    {0}", home->PropertyNumber);
        Console::WriteLine("Address:       {0}\n              {1}, {2} {3}",
    	                home->Address, home->City,
    			home->State, home->ZIPCode);
        Console::WriteLine("Condition:     {0}", home->Condition);
        Console::WriteLine("Style:         {0}", home->Style);
        Console::WriteLine("Bedrooms:      {0}", home->Bedrooms);
        Console::WriteLine("Bathrooms:     {0}", home->Bathrooms);
        Console::WriteLine("Stories:       {0}", home->Stories);
        Console::WriteLine("Year Built:    {0}", home->YearBuilt);
        Console::WriteLine("Garage Spaces: {0} SqFt", home->NumberOfGarageSpaces);
        Console::WriteLine("Lot Size:      {0:F}", home->LotSizeInSqFt);
        Console::WriteLine("Market Value:  {0:C}", home->MarketValue);
    
        Console::WriteLine();
        return 0;
    }
  2. Execute the application to test it. Here is an example:

  3.  
    Screen 1
    =//= Altair Realty =//=
    -=- Properties Inventory -=-
    To create a listing, enter the following information
    Property #:    258904
    Property Condition
    0. Unknown
    1. Excellent
    2. Good (may need minor repair
    3. Acceptable (needs major repair)
    4. Even (land is more important)
    Your Choice:    2
    Street Address: 824 Green Castle Rd
    City:           Silver Spring
    State:          MD
    ZIP Code:       20906
    Bedrooms:       5
    Bathrooms:      2.5
    Stories:        3
    Year Built: 1972
    Style
    U. Unknown
    S. Split Level
    C. Colonial
    G. Georgial
    Your Choice:    G
    Garage Spaces:  0
    Total Lot Size: 5688.82
    Market Value:   645840
    Screen 2
    =//= Altair Realty =//=
    -=- Properties Inventory -=-
    =//= Property Listing =//=
    Property #:    258904
    Address:       824 Green Castle Rd
                   Silver Spring, MD 20906
    Condition:     2
    Style:         G
    Bedrooms:      5
    Bathrooms:     2.5
    Stories:       3
    Year Built:    1972
    Garage Spaces: 0
    Lot Size:      5688.82
    Market Value:  $645,840.00
    
    Press any key to continue . . .
  4. Close the DOS window
 

Previous Copyright © 2006-2016, FunctionX, Inc. Next