Home

Data Reading and Formatting

 

Data Reading

 

Introduction

The Console class uses Write() or WriteLine() to display values in the DOS window. As opposed to displaying something on the screen, you may want to request a value from the user. To support this, the Console class provides the Read() method. To use it, the name of a variable can be assigned to it. The syntax used is:

VariableName = Console.Read()

When the user types something and presses Enter, what the user had typed would be assigned to the variable specified on the left side of the assignment operator.

Read() doesn't always have to assign its value to a variable. For example, it can be used on its own line, which simply means that the user is expected to type something but the value typed by the user would not be used for any significant purpose. For example, you can use the Read() function to wait for the user to press any key in order to close the DOS window.

Besides Read(), the Console class also provides ReadLine(). Like WriteLine(), after performing its assignment, ReadLine() sends the caret to the next line. Otherwise, it plays the same role as the Read() function.

Practical LearningPractical Learning: Introducing Data Reading

  1. Start Notepad and, in the empty file, type the following:
     
    Imports System
    
    Module Module1
        Sub Main()
    
        End Sub
    
    End Module
  2. Save the file in a new folder called GCS1 inside your VBasic folder
  3. Save the file itself as Exercise.cs

String Value Request 

In most assignments of your programs, you will not know the value of a string when writing your application. For example, you may want the user to provide such a string. To request a string (or any of the variables we will see in this lesson), you can call the Console.Read() or the Console.ReadLine() function and assign it to the name of the variable whose value you want to retrieve. Here is an example:

Module Module1

    Sub Main()
        Dim FirstName As String
        Console.Write("Enter First Name: ")
        FirstName = Console.ReadLine()
    End Sub

End Module
 
 

Practical LearningPractical Learning: Reading String Values

  1. To request strings from the user, change the file as follows:
     
    Imports System
    
    Module Module1
        Sub Main()
            Dim CustomerName As String
     	Dim HomePhone As String
    
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	' Request customer information from the user
    	Console.Write("Enter Customer Name:  ")
    	CustomerName = Console.ReadLine()
    	Console.Write("Enter Customer Phone: ")
    	HomePhone = Console.ReadLine()
    
    	Console.WriteLine()
            	' Display the receipt
    	Console.WriteLine("====================================")
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	Console.WriteLine("====================================")
    	Console.WriteLine("Customer:   " + CustomerName)
    	Console.WriteLine("Home Phone: " + HomePhone)
    	Console.WriteLine("====================================")
        End Sub
    End Module
  2. Save the file
  3. Open the Command Prompt and change to the above Drive:\VBasic\GCS1 folder
  4. To compile the program, type vbc /out:"Georgetown Cleaning Services".exe exercise.vb and press Enter
  5. To execute the program, type "Georgetown Cleaning Services" and press Enter. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  James Watson
    Enter Customer Phone: (410) 493-2005
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Watson
    Home Phone: (410) 493-2005
    ====================================
  6. Return to Notepad

Number Request

Everything the user types is a string. If you want to get a number from the user, first request a string. Here is an example:

Module Module1

    Sub Main()
        Dim Number As Integer
        Dim strNumber As String

        Console.Write("Enter a natural number: ")
        strNumber = Console.ReadLine()
    End Sub

End Module

After getting the string, you must convert it to a number. To perform this conversion, you can use one of the conversion functions we mentioned in Lesson 2 for each data type. Here is an example:

Module Module1

    Sub Main()
        Dim Number As Integer
        Dim dblNumber As Integer
        Dim strNumber As String

        Console.Write("Enter a natural number: ")
        strNumber = Console.ReadLine()
        Number = CInt(strNumber)

        dblNumber = Number * 2
        Console.WriteLine("Number: " + CStr(dblNumber))
    End Sub

End Module

An advanced but faster way to do this is to type Console.ReadLine() in the parentheses of the conversion function. This has the same effect. Here is an example:

Module Module1

    Sub Main()
        Dim Number As Integer
        Dim dblNumber As Integer

        Console.Write("Enter a natural number: ")
        Number = CInt(Console.ReadLine())

        dblNumber = Number * 2
        Console.WriteLine("Number: " + CStr(dblNumber))
    End Sub

End Module

 

Practical LearningPractical Learning: Reading Numeric Values

  1. To retrieve various numbers from the user, change the file as follows:
     
    Imports System
    
    Module Module1
        Sub Main()
            ' Price of items
    	Const PriceOneShirt As Double     = 0.95D
    	Const PriceAPairOfPants As Double = 2.95D
    	Const PriceOneDress As Double     = 4.55D
    	Const TaxRate As Double           = 0.0575D  ' 5.75%
    
    	' Customer personal infoirmation
    	Dim CustomerName As String
    	Dim HomePhone As String
    	' Unsigned numbers to represent cleaning items
    	Dim NumberOfShirts As Integer
    	Dim NumberOfPants As Integer
    	Dim NumberOfDresses As Integer
    	' Each of these sub totals will be used for cleaning items
    	Dim SubTotalShirts As Double
    	Dim SubTotalPants As Double
    	Dim SubTotalDresses As Double
    	' Values used to process an order
    	Dim TotalOrder As Double
    	Dim TaxAmount As Double
    	Dim SalesTotal As Double
    	Dim AmountTended As Double
    	Dim Difference As Double
    
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	' Request customer information from the user
    	Console.Write("Enter Customer Name:  ")
    	CustomerName = Console.ReadLine()
    	Console.Write("Enter Customer Phone: ")
    	HomePhone = Console.ReadLine()
    			
    	' Request the quantity of each category of items
    	Console.Write("Number of Shirts:  ")
    	Dim strShirts As String = Console.ReadLine()
    	NumberOfShirts   = CInt(strShirts)
    			
    	Console.Write("Number of Pants:   ")
    	Dim strPants As String = Console.ReadLine()
    	NumberOfPants    = CInt(strPants)
    			
    	Console.Write("Number of Dresses: ")
    	Dim strDresses As String = Console.ReadLine()
    	NumberOfDresses   = CInt(strDresses)
    			
    	' Perform the necessary calculations
    	SubTotalShirts  = NumberOfShirts  * PriceOneShirt
    	SubTotalPants   = NumberOfPants   * PriceAPairOfPants
    	SubTotalDresses = NumberOfDresses * PriceOneDress
    	' Calculate the "temporary" total of the order
    	TotalOrder      = SubTotalShirts + SubTotalPants + SubTotalDresses
    
    	' Calculate the tax amount using a constant rate
    	TaxAmount       = TotalOrder * TaxRate
    	' Add the tax amount to the total order
    	SalesTotal      = TotalOrder + TaxAmount
    
    	' Communicate the total to the user...
    	Console.Write("\nThe Total order is: ")
    	Console.WriteLine(SalesTotal)
    	' and request money for the order
    	Console.Write("Amount Tended? ")
    	AmountTended    = CDbl(Console.ReadLine())
    
    	' Calculate the difference owed to the customer
    	' or that the customer still owes to the store
    	Difference      = AmountTended - SalesTotal
    	Console.WriteLine()
    
    	' Display the receipt
    	Console.WriteLine("====================================")
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	Console.WriteLine("====================================")
    	Console.WriteLine("Customer:   " + CustomerName)
    	Console.WriteLine("Home Phone: " + HomePhone)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Item Type  Qty Unit/Price Sub-Total")
    	Console.WriteLine("------------------------------------")
    	Console.Write("Shirts      ")
    	Console.Write(NumberOfShirts)
    	Console.Write("     ")
    	Console.Write(PriceOneShirt)
    	Console.Write("     ")
    	Console.WriteLine(SubTotalShirts)
    	Console.Write("Pants       ")
    	Console.Write(NumberOfPants)
    	Console.Write("     ")
    	Console.Write(PriceAPairOfPants)
    	Console.Write("     ")
    	Console.WriteLine(SubTotalPants)
    	Console.Write("Dresses     ")
    	Console.Write(NumberOfDresses)
    	Console.Write("     ")
    	Console.Write(PriceOneDress)
    	Console.Write("     ")
    	Console.WriteLine(SubTotalDresses)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Total Order:     " + CStr(TotalOrder))
    	Console.WriteLine("Tax Rate:        " + CStr(TaxRate * 100) + "%")
    	Console.WriteLine("Tax Amount:      " + CStr(TaxAmount))
    	Console.WriteLine("Net Price:       " + CStr(SalesTotal))
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Amount Tended:   " + CStr(AmountTended))
    	Console.WriteLine("Difference:      " + CStr(Difference))
    	Console.WriteLine("====================================")
        End Sub
    End Module
  2. Save the file
  3. At the Command Prompt, change to the GCS3 folder
  4. To compile the program, type 
    csc /out:"Georgetown Cleaning Services".exe Exercise.cs
    and press Enter
  5. To execute the program, type "Georgetown Cleaning Services" and press Enter. Here is an example of running the program:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  Genevieve Alton
    Enter Customer Phone: (202) 974-8244
    Number of Shirts:  8
    Number of Pants:   2
    Number of Dresses: 3
    
    The Total order is: 28.711125
    Amount Tended? 30
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   Genevieve Alton
    Home Phone: (202) 974-8244
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      8     0.95     7.60
    Pants       2     2.95     5.90
    Dresses     3     4.55     13.65
    ------------------------------------
    Total Order:     27.15
    Tax Rate:        5.7500%
    Tax Amount:      1.561125
    Net Price:       28.711125
    ------------------------------------
    Amount Tended:   30
    Difference:      1.288875
    ====================================
  6. Return to Notepad
 

Requesting Dates and Times

As done with the regular numbers, you can request a date value from the user. This is also done by requesting a string from the user. Here is an example:

Module Module1

    Sub Main()
        Dim strDateHired As String

        strDateHired = Console.ReadLine()
    End Sub

End Module

After the user has entered the string you can then convert it to a Date value using CDate() as we mentioned in Lesson 2.

By default, if you request only a date from the user and the user enters a valid date, the compiler would add the midnight value to the date. If you request only the time from the user and the user enters a valid time, the compiler would add the current date to the value. Later on, we will learn how to isolate either only the date or only the time.

Practical LearningPractical Learning: Requesting Date and Time Values

  1. To deal with new dates and times, change the program as follows:
     
    Imports System
    
    Module Module1
        Sub Main()
            ' Price of items
    	Const PriceOneShirt As Double     = 0.95D
    	Const PriceAPairOfPants As Double = 2.95D
    	Const PriceOneDress As Double     = 4.55D
    	Const TaxRate As Double           = 0.0575D  ' 5.75%
    
    	' Customer personal infoirmation
    	Dim CustomerName As String
    	Dim HomePhone As String
    	Dim OrderDate As Date 
    
    	' Unsigned numbers to represent cleaning items
    	Dim NumberOfShirts As Integer
    	Dim NumberOfPants As Integer
    	Dim NumberOfDresses As Integer
    	' Each of these sub totals will be used for cleaning items
    	Dim SubTotalShirts As Double
    	Dim SubTotalPants As Double
    	Dim SubTotalDresses As Double
    	' Values used to process an order
    	Dim TotalOrder As Double
    	Dim TaxAmount As Double
    	Dim SalesTotal As Double
    	Dim AmountTended As Double
    	Dim Difference As Double
    
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	' Request customer information from the user
    	Console.Write("Enter Customer Name:  ")
    	CustomerName = Console.ReadLine()
    	Console.Write("Enter Customer Phone: ")
    	HomePhone = Console.ReadLine()
    	Console.WriteLine("Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)")
    	OrderDate = CDate(Console.ReadLine())
    			
    	' Request the quantity of each category of items
    	Console.Write("Number of Shirts:  ")
    	Dim strShirts As String = Console.ReadLine()
    	NumberOfShirts   = CInt(strShirts)
    			
    	Console.Write("Number of Pants:   ")
    	Dim strPants As String = Console.ReadLine()
    	NumberOfPants    = CInt(strPants)
    			
    	Console.Write("Number of Dresses: ")
    	Dim strDresses As String = Console.ReadLine()
    	NumberOfDresses   = CInt(strDresses)
    			
    	' Perform the necessary calculations
    	SubTotalShirts  = NumberOfShirts  * PriceOneShirt
    	SubTotalPants   = NumberOfPants   * PriceAPairOfPants
    	SubTotalDresses = NumberOfDresses * PriceOneDress
    	' Calculate the "temporary" total of the order
    	TotalOrder      = SubTotalShirts + SubTotalPants + SubTotalDresses
    
    	' Calculate the tax amount using a constant rate
    	TaxAmount       = TotalOrder * TaxRate
    	' Add the tax amount to the total order
    	SalesTotal      = TotalOrder + TaxAmount
    
    	' Communicate the total to the user...
    	Console.Write("\nThe Total order is: ")
    	Console.WriteLine(SalesTotal)
    	' and request money for the order
    	Console.Write("Amount Tended? ")
    	AmountTended    = CDbl(Console.ReadLine())
    
    	' Calculate the difference owed to the customer
    	' or that the customer still owes to the store
    	Difference      = AmountTended - SalesTotal
    	Console.WriteLine()
    
    	' Display the receipt
    	Console.WriteLine("====================================")
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	Console.WriteLine("====================================")
    	Console.WriteLine("Customer:   " + CustomerName)
    	Console.WriteLine("Home Phone: " + HomePhone)
    	Console.WriteLine("Date & Time: " + CStr(OrderDate))
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Item Type  Qty Unit/Price Sub-Total")
    	Console.WriteLine("------------------------------------")
    	Console.Write("Shirts      ")
    	Console.Write(NumberOfShirts)
    	Console.Write("     ")
    	Console.Write(PriceOneShirt)
    	Console.Write("     ")
    	Console.WriteLine(SubTotalShirts)
    	Console.Write("Pants       ")
    	Console.Write(NumberOfPants)
    	Console.Write("     ")
    	Console.Write(PriceAPairOfPants)
    	Console.Write("     ")
    	Console.WriteLine(SubTotalPants)
    	Console.Write("Dresses     ")
    	Console.Write(NumberOfDresses)
    	Console.Write("     ")
    	Console.Write(PriceOneDress)
    	Console.Write("     ")
    	Console.WriteLine(SubTotalDresses)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Total Order:     " + CStr(TotalOrder))
    	Console.WriteLine("Tax Rate:        " + CStr(TaxRate * 100) + "%")
    	Console.WriteLine("Tax Amount:      " + CStr(TaxAmount))
    	Console.WriteLine("Net Price:       " + CStr(SalesTotal))
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Amount Tended:   " + CStr(AmountTended))
    	Console.WriteLine("Difference:      " + CStr(Difference))
    	Console.WriteLine("====================================")
        End Sub
    End Module
  2. Save the file
  3. At the Command Prompt, change to the GCS3 folder
  4. To compile the program, type 
    csc /out:"Georgetown Cleaning Services".exe Exercise.cs
    and press Enter
  5. To execute the program, type "Georgetown Cleaning Services" and press Enter. Here is an example of running the program:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  Alexander Pappas
    Enter Customer Phone: (301) 397-9764
    Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)
    06/22/98 08:26 AM
    Number of Shirts:  2
    Number of Pants:   6
    Number of Dresses: 0
    
    The Total order is: 20.727000
    Amount Tended? 50
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Alexander Pappas
    Home Phone:  (301) 397-9764
    Date & Time: 6/22/1998 8:26:00 AM
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      2     0.95     1.90
    Pants       6     2.95     17.70
    Dresses     0     4.55     0
    ------------------------------------
    Total Order:     19.60
    Tax Rate:        5.7500%
    Tax Amount:      1.127000
    Net Price:       20.727000
    ------------------------------------
    Amount Tended:   50
    Difference:      29.273000
    ====================================
  6. Return to Notepad

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 directly. To do this, you can provide two strings to the 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 would 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:

Module Module1

    Sub Main()
        Dim FullName As String = "Anselme Bogos"
        Dim Age As Integer = 15
        Dim HSalary As Double = 22.74

        Console.WriteLine("Full Name: {0}", FullName)
        Console.WriteLine("Age: {0}", Age)
        Console.WriteLine("Distance: {0}", HSalary)
    End Sub

End Module

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} {n}", First, Second, Third, nth)

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

Practical LearningPractical Learning: Displaying Data With Placeholders

  1. To use curly brackets to display data, change the file as follows:
     
    Imports System
    
    Module Module1
        Sub Main()
            ' Price of items
    	Const PriceOneShirt As Double     = 0.95D
    	Const PriceAPairOfPants As Double = 2.95D
    	Const PriceOneDress As Double     = 4.55D
    	Const TaxRate As Double           = 0.0575D  ' 5.75%
    
    	' Customer personal infoirmation
    	Dim CustomerName As String
    	Dim HomePhone As String
    	Dim OrderDate As Date 
    
    	' Unsigned numbers to represent cleaning items
    	Dim NumberOfShirts As Integer
    	Dim NumberOfPants As Integer
    	Dim NumberOfDresses As Integer
    	' Each of these sub totals will be used for cleaning items
    	Dim SubTotalShirts As Double
    	Dim SubTotalPants As Double
    	Dim SubTotalDresses As Double
    	' Values used to process an order
    	Dim TotalOrder As Double
    	Dim TaxAmount As Double
    	Dim SalesTotal As Double
    	Dim AmountTended As Double
    	Dim Difference As Double
    
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	' Request customer information from the user
    	Console.Write("Enter Customer Name:  ")
    	CustomerName = Console.ReadLine()
    	Console.Write("Enter Customer Phone: ")
    	HomePhone = Console.ReadLine()
    	Console.WriteLine("Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)")
    	OrderDate = CDate(Console.ReadLine())
    			
    	' Request the quantity of each category of items
    	Console.Write("Number of Shirts:  ")
    	Dim strShirts As String = Console.ReadLine()
    	NumberOfShirts   = CInt(strShirts)
    			
    	Console.Write("Number of Pants:   ")
    	Dim strPants As String = Console.ReadLine()
    	NumberOfPants    = CInt(strPants)
    			
    	Console.Write("Number of Dresses: ")
    	Dim strDresses As String = Console.ReadLine()
    	NumberOfDresses   = CInt(strDresses)
    			
    	' Perform the necessary calculations
    	SubTotalShirts  = NumberOfShirts  * PriceOneShirt
    	SubTotalPants   = NumberOfPants   * PriceAPairOfPants
    	SubTotalDresses = NumberOfDresses * PriceOneDress
    	' Calculate the "temporary" total of the order
    	TotalOrder      = SubTotalShirts + SubTotalPants + SubTotalDresses
    
    	' Calculate the tax amount using a constant rate
    	TaxAmount       = TotalOrder * TaxRate
    	' Add the tax amount to the total order
    	SalesTotal      = TotalOrder + TaxAmount
    
    	' Communicate the total to the user...
    	Console.Write("\nThe Total order is: ")
    	Console.WriteLine(SalesTotal)
    	' and request money for the order
    	Console.Write("Amount Tended? ")
    	AmountTended    = CDbl(Console.ReadLine())
    
    	' Calculate the difference owed to the customer
    	' or that the customer still owes to the store
    	Difference      = AmountTended - SalesTotal
    	Console.WriteLine()
    
    	' Display the receipt
    	Console.WriteLine("====================================")
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	Console.WriteLine("====================================")
    	Console.WriteLine("Customer:    {0}", CustomerName)
    	Console.WriteLine("Home Phone:  {0}", HomePhone)
    	Console.WriteLine("Date & Time: {0}", OrderDate)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Item Type  Qty Unit/Price Sub-Total")
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Shirts      {0}     {1}     {2}", _
    			NumberOfShirts, PriceOneShirt, SubTotalShirts)
    	Console.WriteLine("Pants       {0}     {1}     {2}", _
    			NumberOfPants, PriceAPairOfPants, SubTotalPants)
    	Console.WriteLine("Dresses     {0}     {1}     {2}", _
    		          NumberOfDresses, PriceOneDress, SubTotalDresses)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Total Order:     {0}", TotalOrder)
    	Console.WriteLine("Tax Rate:        {0}%", TaxRate * 100)
    	Console.WriteLine("Tax Amount:      {0}", TaxAmount)
    	Console.WriteLine("Net Price:       {0}", SalesTotal)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Amount Tended:   {0}", AmountTended)
    	Console.WriteLine("Difference:      {0}", Difference)
    	Console.WriteLine("====================================")
        End Sub
    End Module
  2. Save, compile, and execute the program

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. Normally, in C#, as we mentioned with boxing, and as we have done so far, this conversion is automatically or transparently done by the compiler. In some cases, you will need to perform the conversion yourself.

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

Module Module1

    Sub Main()
        Dim FullName As String = "Anselme Bogos"
        Dim Age As Integer = 15
        Dim HSalary As Double = 22.74

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

End Module

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. As it happens, 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 letter 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:

Module Module1

    Sub Main()
        Dim Distance As Double = 248.38782
        Dim Age As Integer = 15
        Dim NewColor As Integer = 3478
        Dim HourlySalary As Double = 22.74
        Dim HoursWorked As Double = 35.5018473
        Dim WeeklySalary As Double = HourlySalary * HoursWorked

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

End Module

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.

 

Practical LearningPractical Learning: Formatting Data Display

  1. To format data display, change the file as follows:
     
    Imports System
    
    Module Module1
        Sub Main()
            ' Price of items
    	Const PriceOneShirt As Double     = 0.95D
    	Const PriceAPairOfPants As Double = 2.95D
    	Const PriceOneDress As Double     = 4.55D
    	Const TaxRate As Double           = 0.0575D  ' 5.75%
    
    	' Customer personal infoirmation
    	Dim CustomerName As String
    	Dim HomePhone As String
    	Dim OrderDate As Date 
    
    	' Unsigned numbers to represent cleaning items
    	Dim NumberOfShirts As Integer
    	Dim NumberOfPants As Integer
    	Dim NumberOfDresses As Integer
    	' Each of these sub totals will be used for cleaning items
    	Dim SubTotalShirts As Double
    	Dim SubTotalPants As Double
    	Dim SubTotalDresses As Double
    	' Values used to process an order
    	Dim TotalOrder As Double
    	Dim TaxAmount As Double
    	Dim SalesTotal As Double
    	Dim AmountTended As Double
    	Dim Difference As Double
    
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	' Request customer information from the user
    	Console.Write("Enter Customer Name:  ")
    	CustomerName = Console.ReadLine()
    	Console.Write("Enter Customer Phone: ")
    	HomePhone = Console.ReadLine()
    	Console.WriteLine("Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)")
    	OrderDate = CDate(Console.ReadLine())
    			
    	' Request the quantity of each category of items
    	Console.Write("Number of Shirts:  ")
    	Dim strShirts As String = Console.ReadLine()
    	NumberOfShirts   = CInt(strShirts)
    			
    	Console.Write("Number of Pants:   ")
    	Dim strPants As String = Console.ReadLine()
    	NumberOfPants    = CInt(strPants)
    			
    	Console.Write("Number of Dresses: ")
    	Dim strDresses As String = Console.ReadLine()
    	NumberOfDresses   = CInt(strDresses)
    			
    	' Perform the necessary calculations
    	SubTotalShirts  = NumberOfShirts  * PriceOneShirt
    	SubTotalPants   = NumberOfPants   * PriceAPairOfPants
    	SubTotalDresses = NumberOfDresses * PriceOneDress
    	' Calculate the "temporary" total of the order
    	TotalOrder      = SubTotalShirts + SubTotalPants + SubTotalDresses
    
    	' Calculate the tax amount using a constant rate
    	TaxAmount       = TotalOrder * TaxRate
    	' Add the tax amount to the total order
    	SalesTotal      = TotalOrder + TaxAmount
    
    	' Communicate the total to the user...
    	Console.Write("\nThe Total order is: ")
    	Console.WriteLine(SalesTotal)
    	' and request money for the order
    	Console.Write("Amount Tended? ")
    	AmountTended    = CDbl(Console.ReadLine())
    
    	' Calculate the difference owed to the customer
    	' or that the customer still owes to the store
    	Difference      = AmountTended - SalesTotal
    	Console.WriteLine()
    
    	' Display the receipt
    	Console.WriteLine("====================================")
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	Console.WriteLine("====================================")
    	Console.WriteLine("Customer:    {0}", CustomerName)
    	Console.WriteLine("Home Phone:  {0}", HomePhone)
    	Console.WriteLine("Date & Time: {0}", OrderDate)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Item Type  Qty Unit/Price Sub-Total")
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Shirts      {0}     {1:C}     {2}", _
    			NumberOfShirts, PriceOneShirt, SubTotalShirts.ToString("C"))
    	Console.WriteLine("Pants       {0}     {1}     {2:C}", _
    			NumberOfPants, PriceAPairOfPants.ToString("C"), SubTotalPants)
    	Console.WriteLine("Dresses     {0}     {1:C}     {2:C}", _
    		          NumberOfDresses, PriceOneDress, SubTotalDresses)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Total Order:     {0:C}", TotalOrder)
    	Console.WriteLine("Tax Rate:        {0:P}", TaxRate)
    	Console.WriteLine("Tax Amount:      {0}", TaxAmount.ToString("C"))
    	Console.WriteLine("Net Price:       {0:F}", SalesTotal)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Amount Tended:   {0:C}", AmountTended)
    	Console.WriteLine("Difference:      {0:C}", Difference)
    	Console.WriteLine("====================================")
        End Sub
    End Module
  2. Save it and switch to the Command Prompt. Then compile the file and execute the application. Here is an example:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  Gretchen McCormack
    Enter Customer Phone: (410) 739-2884
    Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)
    04/09/2001 10:25 AM
    Number of Shirts:  5
    Number of Pants:   12
    Number of Dresses: 8
    
    The Total order is: 80.951625
    Amount Tended? 100
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Gretchen McCormack
    Home Phone:  (410) 739-2884
    Date & Time: 4/9/2001 10:25:00 AM
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     $0.95     $4.75
    Pants       12     $2.95     $35.40
    Dresses     8     $4.55     $36.40
    ------------------------------------
    Total Order:     $76.55
    Tax Rate:        5.75 %
    Tax Amount:      $4.40
    Net Price:       80.95
    ------------------------------------
    Amount Tended:   $100.00
    Difference:      $19.05
    ====================================
  3. Return to Notepad

Line Formatting

In the above programs, to display a line of text, we easily 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 highly format how a string or a line of text should display. The .NET Framework provides 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 placer 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:

Module Module1

    Sub Main()
        Dim FullName As String = "Anselme Bogos"
        Dim Age As Integer = 15
        Dim HourlySalary As Double = 22.74

        Console.WriteLine("Full Name: {0,20}", FullName)
        Console.WriteLine("Age:{0,14}", Age.ToString())
        Console.WriteLine("Distance: {0:C,8}", HourlySalary.ToString())
    End Sub

End Module

This would produce:

Full Name:        Anselme Bogos
Age:            15
Distance: 22.74

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.

Data and Time Formatting

As mentioned earlier, when the user enters a date value for a DateTime variable, the compiler adds a time part to the value. Fortunately, if you want to consider only the date or only the time part, you can specify this to the compiler. To support this, the DateTime data type provides a series of letters you can use to format how its value should be displayed to the user. The character is entered in the placeholder of the DateTime variable after the 0 or the incremental numeric value.

Practical LearningPractical Learning: Controlling Date/Time Formatting

  1. To control formatting of date and time, change the file as follows:
     
    Imports System
    
    Module Module1
        Sub Main()
            ' Price of items
    	Const PriceOneShirt As Double     = 0.95D
    	Const PriceAPairOfPants As Double = 2.95D
    	Const PriceOneDress As Double     = 4.55D
    	Const TaxRate As Double           = 0.0575D  ' 5.75%
    
    	' Customer personal infoirmation
    	Dim CustomerName As String
    	Dim HomePhone As String
    	Dim OrderDate As Date
    	Dim OrderTime As Date
    
    	' Unsigned numbers to represent cleaning items
    	Dim NumberOfShirts As Integer
    	Dim NumberOfPants As Integer
    	Dim NumberOfDresses As Integer
    	' Each of these sub totals will be used for cleaning items
    	Dim SubTotalShirts As Double
    	Dim SubTotalPants As Double
    	Dim SubTotalDresses As Double
    	' Values used to process an order
    	Dim TotalOrder As Double
    	Dim TaxAmount As Double
    	Dim SalesTotal As Double
    	Dim AmountTended As Double
    	Dim Difference As Double
    
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	' Request customer information from the user
    	Console.Write("Enter Customer Name:  ")
    	CustomerName = Console.ReadLine()
    	Console.Write("Enter Customer Phone: ")
    	HomePhone = Console.ReadLine()
    	Console.Write("Enter the order date(mm/dd/yyyy):  ")
    	OrderDate = CDate(Console.ReadLine())
    	Console.Write("Enter the order time(hh:mm AM/PM): ")
    	OrderTime = CDate(Console.ReadLine())
    			
    	' Request the quantity of each category of items
    	Console.Write("Number of Shirts:  ")
    	Dim strShirts As String = Console.ReadLine()
    	NumberOfShirts   = CInt(strShirts)
    			
    	Console.Write("Number of Pants:   ")
    	Dim strPants As String = Console.ReadLine()
    	NumberOfPants    = CInt(strPants)
    			
    	Console.Write("Number of Dresses: ")
    	Dim strDresses As String = Console.ReadLine()
    	NumberOfDresses   = CInt(strDresses)
    			
    	' Perform the necessary calculations
    	SubTotalShirts  = NumberOfShirts  * PriceOneShirt
    	SubTotalPants   = NumberOfPants   * PriceAPairOfPants
    	SubTotalDresses = NumberOfDresses * PriceOneDress
    	' Calculate the "temporary" total of the order
    	TotalOrder      = SubTotalShirts + SubTotalPants + SubTotalDresses
    
    	' Calculate the tax amount using a constant rate
    	TaxAmount       = TotalOrder * TaxRate
    	' Add the tax amount to the total order
    	SalesTotal      = TotalOrder + TaxAmount
    
    	' Communicate the total to the user...
    	Console.Write("\nThe Total order is: ")
    	Console.WriteLine(SalesTotal)
    	' and request money for the order
    	Console.Write("Amount Tended? ")
    	AmountTended    = CDbl(Console.ReadLine())
    
    	' Calculate the difference owed to the customer
    	' or that the customer still owes to the store
    	Difference      = AmountTended - SalesTotal
    	Console.WriteLine()
    
    	' Display the receipt
    	Console.WriteLine("====================================")
    	Console.WriteLine("-/- Georgetown Cleaning Services -/-")
    	Console.WriteLine("====================================")
    	Console.WriteLine("Customer:    {0}", CustomerName)
    	Console.WriteLine("Home Phone:  {0}", HomePhone)
    	Console.WriteLine("Order Date:  {0:D}", OrderDate)
    	Console.WriteLine("Order Time:  {0:t}", OrderTime)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Item Type  Qty Unit/Price Sub-Total")
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Shirts      {0}     {1:C}     {2}", _
    			NumberOfShirts, PriceOneShirt, SubTotalShirts.ToString("C"))
    	Console.WriteLine("Pants       {0}     {1}     {2}", _
    			NumberOfPants, PriceAPairOfPants, SubTotalPants)
    	Console.WriteLine("Dresses     {0}     {1:C}     {2:C}", _
    		          NumberOfDresses, PriceOneDress, SubTotalDresses)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Total Order:     {0:C}", TotalOrder)
    	Console.WriteLine("Tax Rate:        {0:P}", TaxRate)
    	Console.WriteLine("Tax Amount:      {0}", TaxAmount.ToString("C"))
    	Console.WriteLine("Net Price:       {0:F}", SalesTotal)
    	Console.WriteLine("------------------------------------")
    	Console.WriteLine("Amount Tended:   {0:C}", AmountTended)
    	Console.WriteLine("Difference:      {0:C}", Difference)
    	Console.WriteLine("====================================")
        End Sub
    End Module
  2. Save, compile, and run the program. Here is an example:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  Antoinette Calhoun
    Enter Customer Phone: (703) 797-1135
    Enter the order date(mm/dd/yyyy):  04/12/2002
    Enter the order time(hh:mm AM/PM): 2:12 PM
    Number of Shirts:  5
    Number of Pants:   2
    Number of Dresses: 1
    
    The Total order is: $16.07
    Amount Tended? 20
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Antoinette Calhoun
    Home Phone:  (703) 797-1135
    Order Date:  Friday, April 12, 2002
    Order Time:  2:12 PM
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts     5   $0.95       $4.75
    Pants      2   $2.95        $5.90
    Dresses    1   $4.55        $4.55
    ------------------------------------
    Total Order:   $15.20
    Tax Rate:      5.75 %
    Tax Amount:    $0.87
    Net Price:     $16.07
    ------------------------------------
    Amount Tended: $20.00
    Difference:    $3.93
    ====================================
  3. Type Exit and close Notepad
 

Previous Copyright © 2004-2007 FunctionX, Inc. Next