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:
|
Here are examples: using System; // An Exercise class class Exercise { static void Main() { String FullName = "Anselme Bogos"; int Age = 15; double HSalary = 22.74; Console.WriteLine("Full Name: {0}", FullName); Console.WriteLine("Age: {0}", Age); Console.WriteLine("Distance: {0}", HSalary); Console.WriteLine(); } } 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.
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: using System; // An Exercise class class Exercise { static void Main() { String FullName = "Anselme Bogos"; int Age = 15; double HSalary = 22.74; Console.WriteLine("Full Name: {0}", FullName); Console.WriteLine("Age: {0}", Age.ToString()); Console.WriteLine("Distance: {0}", HSalary.ToString()); Console.WriteLine(); } } In some cases, you will type something in the parentheses of ToString().
|
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:
Here are examples: using System; // An Exercise class class Exercise { static void Main() { double Distance = 248.38782; int Age = 15; int NewColor = 3478; double HSalary = 22.74, HoursWorked = 35.5018473; double WeeklySalary = HSalary * 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")); Console.WriteLine(); } } 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 Learning: Formatting Data Display |
using System; namespace GeorgetownCleaningServices3 { class OrderProcessing { static void Main() { // Price of items const decimal PriceOneShirt = 0.95M; const decimal PriceAPairOfPants = 2.95M; const decimal PriceOneDress = 4.55M; const decimal TaxRate = 5.75M; // 5.75% // Basic information about an order string CustomerName, HomePhone; DateTime OrderDate; // Unsigned numbers to represent cleaning items uint NumberOfShirts, NumberOfPants, NumberOfDresses; // Each of these sub totals will be used for cleaning items decimal SubTotalShirts, SubTotalPants, SubTotalDresses; // Values used to process an order decimal TotalOrder, TaxAmount, SalesTotal; decimal AmountTended, Difference; Console.WriteLine("-/- Georgetown Cleaning Services -/-"); // Request order 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 = DateTime.Parse(Console.ReadLine()); // Request the quantity of each category of items Console.Write("Number of Shirts: "); NumberOfShirts = uint.Parse(Console.ReadLine()); Console.Write("Number of Pants: "); NumberOfPants = uint.Parse(Console.ReadLine()); Console.Write("Number of Dresses: "); NumberOfDresses = uint.Parse(Console.ReadLine()); // 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 = decimal.Parse(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.ToString(), PriceOneShirt, SubTotalShirts.ToString("C")); Console.WriteLine("Pants {0} {1:C} {2:C}", 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("===================================="); } } } |
-/- 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 ==================================== |
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: using System; // An Exercise class class Exercise { static void Main() { String FullName = "Anselme Bogos"; int Age = 15; double HSalary = 22.74; Console.WriteLine("Full Name: {0,20}", FullName); Console.WriteLine("Age:{0,14}", Age.ToString()); Console.WriteLine("Distance: {0:C,8}", HSalary.ToString()); Console.WriteLine(); } } 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.
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 Learning: Controlling Date/Time Formatting |
using System; namespace GeorgetownCleaningServices3 { class OrderProcessing { static void Main() { // Price of items const decimal PriceOneShirt = 0.95M; const decimal PriceAPairOfPants = 2.95M; const decimal PriceOneDress = 4.55M; const decimal TaxRate = 0.0575M; // 5.75% // Basic information about an order string CustomerName, HomePhone; DateTime OrderDate, OrderTime; // Unsigned numbers to represent cleaning items uint NumberOfShirts, NumberOfPants, NumberOfDresses; // Each of these sub totals will be used for cleaning items decimal SubTotalShirts, SubTotalPants, SubTotalDresses; // Values used to process an order decimal TotalOrder, TaxAmount, SalesTotal; decimal AmountTended, Difference; Console.WriteLine("-/- Georgetown Cleaning Services -/-"); // Request order 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 = DateTime.Parse(Console.ReadLine()); Console.Write("Enter the order time(hh:mm AM/PM): "); OrderTime = DateTime.Parse(Console.ReadLine()); // Request the quantity of each category of items Console.Write("Number of Shirts: "); NumberOfShirts = uint.Parse(Console.ReadLine()); Console.Write("Number of Pants: "); NumberOfPants = uint.Parse(Console.ReadLine()); Console.Write("Number of Dresses: "); NumberOfDresses = uint.Parse(Console.ReadLine()); // 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.WriteLine("\nThe Total order is: {0:C}", SalesTotal); // and request money for the order Console.Write("Amount Tended? "); AmountTended = decimal.Parse(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} {2}", NumberOfShirts.ToString(), PriceOneShirt.ToString("C"), SubTotalShirts.ToString("C")); Console.WriteLine("Pants {0} {1} {2}", NumberOfPants.ToString(), PriceAPairOfPants.ToString("C"), SubTotalPants.ToString("C")); Console.WriteLine("Dresses {0} {1} {2}", NumberOfDresses.ToString(), PriceOneDress.ToString("C"), SubTotalDresses.ToString("C")); Console.WriteLine("------------------------------------"); Console.WriteLine("Total Order: {0}", TotalOrder.ToString("C")); Console.WriteLine("Tax Rate: {0}", TaxRate.ToString("P")); Console.WriteLine("Tax Amount: {0}", TaxAmount.ToString("C")); Console.WriteLine("Net Price: {0}", SalesTotal.ToString("C")); Console.WriteLine("------------------------------------"); Console.WriteLine("Amount Tended: {0}", AmountTended.ToString("C")); Console.WriteLine("Difference: {0}", Difference.ToString("C")); Console.WriteLine("===================================="); } } } |
-/- 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 ==================================== |
|
||
Previous | Copyright © 2006-2016, FunctionX, Inc. | |
|