• Tidak ada hasil yang ditemukan

FORMATTING OUTPUT

Dalam dokumen C# 1: Basic Syntax and Semantics (Halaman 42-46)

4 VARIABLES AND DATA TYPES

Exercise 4: Arithmetic

4.3 FORMATTING OUTPUT

Convert is a class in the namespace System which defines a family of conversion functions.

Note that these, here ToDouble(), requires that the user has actually entered a legitimate number. If not, the program stops with an exception. Next the perimeter and area are calculated:

double p = r * 2 * Math.PI;

double a = r * r * Math.PI;

Here Math.PI is a constant in the class Math which is a class in the System namespace.

Finally the program write the result with WriteLine(), but this time the function has several arguments. The first argument is called a format string and is followed by three variables.

The values of the variables are inserted into the format string determined by the so-called placeholders. For example is {0: F4} a placeholder that indicates that here, the first variable after the format string should be inserted, that is the value of the variable r. The next placeholder is called {1: F4}. It indicates that here the variable p is inserted, the variable number 2 after the format string. F4 means that the value is added as a decimal number (F) with 4 decimals after the decimal point. Similarly, states {2: F4} to be inserted a value formatted as a decimal number with 4 digits. It is in this case, the variable a.

There are following options to format a placeholder:

C Currency (depends on the local setting)

D Integer

E Exponential form (float, double) F Fixed decimal (float, double) G General (F or E)

N Numeric with thousands

X Hexadecimal

The next example performs a calculation, where the user must enter the unit price and number of units of an item. Then the program calculates the total price excl. VAT, VAT, total price incl. VAT and writes the result on the screen:

static void Main(string[] args) {

Console.Write(“Enter the unit price: “);

string text = Console.ReadLine();

double price = Convert.ToDouble(text);

Console.Write(“Enter the number of units: “);

text = Console.ReadLine();

int quantity = Convert.ToInt32(text);

double amount = price * quantity;

double vat = amount * 0.25;

double total = amount + vat;

Console.WriteLine(“{0, -15} {1, 10:F}”, “Unit price”, price);

Console.WriteLine(“{0, -15} {1, 10:D}”,

“Number of units”, quantity);

Console.WriteLine(“{0, -15} {1, 10:F}”, “Total excl. VAT”, amount);

Console.WriteLine(”{0, -15} {1, 10:F}”, ”VAT”, vat);

Console.WriteLine(“{0, -15} {1, 10:F}”, “Total incl. VAT”, total);

}

If you run the program, the result could be the following:

The program works just like the previous program, only this time you must enter two values.

Moreover, the placeholders are more complex. If for example you look at the statement:

Console.WriteLine(“{0, -15} {1, 10:F}”, “Unit price”, price);

there are two placeholders. {0, -15} is the first, and insert the words “Unit price”. -15 means that the field is 15 characters wide, and when the number is negative, the value must be left justified. Note that there is no format character, and then it is the data type of the element that determines the format type. The next placeholder {1, 10:F} means that the next item to be formatted must be right-justified in a field of 10 characters and as a decimal number.

As the number of decimal places is not specified the default value is used, which is 2.

The last example in this section shows how to formats of the result of the type DateTime which is a class representing a date and time:

static void Main(string[] args) {

DateTime dt = DateTime.Now;

Time1(dt);

Time2(dt);

}

static void Time1(DateTime t) {

Console.WriteLine(“{0:D2} {1:D2} {2:D2} {3:D3}”, t.Hour, t.Minute, t.Second, t.Millisecond);

}

static void Time2(DateTime t) {

Console.WriteLine(t.ToLongDateString());

Console.WriteLine(t.ToLongTimeString());

}

In Main() the machine clock is read and its value is stored in a variable:

DateTime dt = DateTime.Now;

DateTime is a class that contains a number of methods to date and time. Now is a property, which always contains the current value of the hardware clock. This value is stored in a variable called dt which type is DateTime. Next, a method Time1() is called, where the variable dt is sent as a parameter. This means that the value is known and can be used in the method Time1() with the name t. The method prints the time in terms of hours, minutes, seconds and milliseconds, each part separated by spaces. You should note the placeholders.

For example means {0: D2} that the first variable to be formatted in a field as an integer, and that the field should be two characters in order to insert a leading 0, if there is only one digit. You will also notice how you refer to the values. t is a variable whose type is DateTime, which is a class. The class defines a number of properties, for example t.Hour for hours, and you refers to the individual characteristics by the variables name followed by a period and the feature name.

The class DateTime provides other opportunities. The method Time2() writes the current date and time, but here I used methods from the DateTime class that formats the result as a string.

If you run the program the result could be:

DateTime is a class (actually a struct), and as you can see, there are some new things such as properties etc.. All this will be dealt with in detail later. The same applies to methods and parameters that are also used in this example without going into detail on the meaning, but you can think of a parameter as a variable that specifies the value a method has to work on. In the examples here, the methods use the value of the variable dt, but it exists and is only known in Main() and is thus not known in the other two methods. We need a mechanism that can transfer dt, when the methods are called, and that’s exactly what parameters are used to.

You should note that in this example there is no particular reason for writing the program using several methods, the aim is also to show the syntax alone, but the use of methods is a central issue for the following.

Dalam dokumen C# 1: Basic Syntax and Semantics (Halaman 42-46)