Manipulating Data Part 2

Total Page:16

File Type:pdf, Size:1020Kb

Manipulating Data Part 2

Manipulating Data Part 2 Numeric and Date Data Types

Numeric data Numbers can be classified as whole numbers i.e. 1, 2, 55, 28466 or fractional numbers i.e. 1.4, 2.454, 456.453. Whole numbers would be used for people’s ages, counting individual items etc where there is no requirement for fractional parts. Fractional numbers are used for actuate measurements, monetary values etc. It is usual in programming to utilise the correct numeric type for you requirements i.e. do not use data types capable of storing large numbers for small values

Exercise Add a new form to your MDI project and name it FrmNumbers. Add 3 textboxes named txtResult, txtNumber1 and txtNumber2 and a button named btnTest Use the new form to carry out the samples in this session

Whole numbers Whole numbers come in various sizes depending on their usage:

 Short – used to store whole numbers in the range -32,768 to 32,767. In previous versions of VB this was the size of the Integer data type – see below  Integer – used to store whole numbers in the range -2,147,483,648 to 2,147,483,647  Long – very large whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807  Int16 – VB .NET equivalent of the Short data type  Int32 – VB .NET equivalent of Integer  Int64 – VB .NET equivalent to Long

If you assign a number to a variable of any of the above data types in design view you will produce an error – blue squiggly line – if you exceed the data types range i.e.

Over the limit – showing error

© Peter Bilbie – 2007-8 Page 1 of 16 Within the higher boundary – no error

Number Conversions – implicit and explicit If you declare a variable to be of an integer data type and assign the value 23.48 to it VB will automatically – implicitly - convert the value to an integer and round it to the nearest whole number i.e. Private Sub btnTest_Click(… Dim num As Integer num = txtNumber1.Text txtNumber2.Text = num End Sub

The result will be:

Notice that numbers over, and including .5 are rounded up - numbers lower than .5 are rounded down We can also explicitly convert from one data type to another with functions and methods available to the developer. In earlier versions of VB you could Cast one variable type to another using the following Casting Functions:

 CInt – cast to an integer value i.e. CInt (2.34)  CSing – cast to a single value i.e. CSing (45)  CDbl – cast to a Double value i.e. CDbl (34)

In VB .NET we have a System.Convert class available that will allow us to do the above conversions and more. However, to use this feature we must set the Option Strict in the properties of the project to ‘on’. If you turn this feature to ‘on’ in your current project you will see numerous conversion errors in your program – see below

© Peter Bilbie – 2007-8 Page 2 of 16 Turn the Option Strict to ‘off’ before you continue with this session If you ensure that the possible result of a calculation will fit in the variable that it will be assigned to then you should not have any problems.

Widening and Narrowing For automatic conversion to be allowed the result of a conversion must not result in loss of data otherwise an error will be raised. Widening conversions are allowed because the type you are converting to is bigger in size i.e. integer to Long. Narrowing is not allowed i.e. Long to Short

Displaying numbers in various formats A computer program will perform numeric calculations for you but result will always be in numeric format – no matter what numeric data type you use i.e.

2 + 2 = 4 2.1 x 2 = 4.2

The calculation may result in a currency value or percentage etc which would benefit from being formatted as we would normally expect i.e. 20% rather than 0.20 £25.65 rather than 25.64898 There are a number of functions and methods we can use to format numerical values – examples of each are shown below

© Peter Bilbie – 2007-8 Page 3 of 16 Currency The accepted data type for currency is Decimal. If we perform a calculation with a mixture of Decimal, single and Integer data types we could assign the result to a Decimal variable. For example to calculate the compound interest paid on a loan using a fixed percentage rate over a known time period (years, months) we could use the following equation:

Amount owed = Principle sum x (1 + (percentage/100)) time period To accomplish this calculation we need to add the input textboxes to our form – see below

We need to add 4 variables to the click event of the Test button which are:

 Principal - Decimal  Percentage – Single (or Decimal)  Years – integer  Result – Decimal Add the following code to the click event of the button: Dim principal, result As Decimal Dim percentage As Single Dim years As Integer

principal = txtPrincipal.Text percentage = txtPercentage.Text years = txtYears.Text

result = principal * ((1 + (percentage / 100)) ^ years)

txtResult.Text = result

© Peter Bilbie – 2007-8 Page 4 of 16 Running the program and testing it with known amounts to calculate a known result i.e. principal 1000, percentage 10 and years 1, result = 1100 - would result in the following:

To format the result to show a currency value we could do one of the following:

txtResult.Text = Format(result, "C")

Or txtResult.Text = Format(result, "Currency") Or

txtResult.Text = result.ToString("C")

Or you could define your own placeholders

txtResult.Text = Format(result, "£#,###.00")

They would all return the following

© Peter Bilbie – 2007-8 Page 5 of 16 String Formats Below is a list of numeric format parameters you can use with the Format function and ToString method – courtesy of Microsoft help files

Format name Description General Number, G, or Displays number with no thousand separator. g Currency, C, or c Displays number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings. Fixed, F, or f Displays at least one digit to the left and two digits to the right of the decimal separator. Standard, N, or n Displays number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator. Percent Displays number multiplied by 100 with a percent sign (%) appended immediately to the right; always displays two digits to the right of the decimal separator. P, or p Displays number with thousandths separator multiplied by 100 with a percent sign (%) appended to the right and separated by a single space; always displays two digits to the right of the decimal separator. Scientific Uses standard scientific notation, providing two significant digits. E, or e Uses standard scientific notation, providing six significant digits. D, or d Displays number as a string that contains the value of the number in Decimal (base 10) format. This option is supported for integral types (Byte, Short, Integer, Long) only. X, or x Displays number as a string that contains the value of the number in Hexadecimal (base 16) format. This option is supported for integral types (Byte, Short, Integer, Long) only. Yes/No Displays No if number is 0; otherwise, displays Yes. True/False Displays False if number is 0; otherwise, displays True. On/Off Displays Off if number is 0; otherwise, displays On.

© Peter Bilbie – 2007-8 Page 6 of 16 String Placeholders You can create your own placeholders with the following parameters Character Description None Displays the number with no formatting. (0) Digit placeholder. Displays a digit or a zero. If the expression has a digit in the position where the zero appears in the format string, display it; otherwise, displays a zero in that position.

If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, displays leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, rounds the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, displays the extra digits without modification. (#) Digit placeholder. Displays a digit or nothing. If the expression has a digit in the position where the # character appears in the format string, displays it; otherwise, displays nothing in that position.

This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has fewer digits than there are # characters on either side of the decimal separator in the format expression. (.) Decimal placeholder. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only # characters to the left of this symbol; numbers smaller than 1 begin with a decimal separator. To display a leading zero displayed with fractional numbers, use zero as the first digit placeholder to the left of the decimal separator. In some locales, a comma is used as the decimal separator. The actual character used as a decimal placeholder in the formatted output depends on the number format recognized by your system. Thus, You should use the period as the decimal placeholder in your formats even if you are in a locale that uses a comma as a decimal placeholder. The formatted string will appear in the format correct for the locale. (%) Percent placeholder. Multiplies the expression by 100. The percent character (%) is inserted in the position where it appears in the format string.

© Peter Bilbie – 2007-8 Page 7 of 16 (,) Thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). A thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) or as the rightmost character in the string means "scale the number by dividing it by 1,000, rounding as needed."

For example, you can use the format string "##0,." to represent 100 million as 100,000. Numbers smaller than 1,000 but greater or equal to 500 are displayed as 1, and numbers smaller than 500 are displayed as 0. Two adjacent thousand separators in this position scale by a factor of 1 million, and an additional factor of 1,000 for each additional separator.

Multiple separators in any position other than immediately to the left of the decimal separator or the rightmost position in the string are treated simply as specifying the use of a thousand separator. In some locales, a period is used as a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system. Thus, You should use the comma as the thousand separator in your formats even if you are in a locale that uses a period as a thousand separator. The formatted string will appear in the format correct for the locale. (:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings. (/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings. (E- E+ e- e+) Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the left of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit placeholders to the left determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents. You must also include digit placeholders to the right of this symbol to get correct formatting. - + $ ( ) Literal characters. These characters are displayed exactly as typed in the format string. To display a character other than one of those listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").

© Peter Bilbie – 2007-8 Page 8 of 16 (,) Thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). A thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) or as the rightmost character in the string means "scale the number by dividing it by 1,000, rounding as needed."

For example, you can use the format string "##0,." to represent 100 million as 100,000. Numbers smaller than 1,000 but greater or equal to 500 are displayed as 1, and numbers smaller than 500 are displayed as 0. Two adjacent thousand separators in this position scale by a factor of 1 million, and an additional factor of 1,000 for each additional separator.

Multiple separators in any position other than immediately to the left of the decimal separator or the rightmost position in the string are treated simply as specifying the use of a thousand separator. In some locales, a period is used as a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system. Thus, You should use the comma as the thousand separator in your formats even if you are in a locale that uses a period as a thousand separator. The formatted string will appear in the format correct for the locale. (\) Displays the next character in the format string. To display a character that has special meaning as a literal character, precede it with a backslash (\). The backslash itself isn't displayed. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (\\).

Examples of characters that can't be displayed as literal characters are the date-formatting and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, /, and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !). ("ABC") Displays the string inside the double quotation marks (" "). To include a string in the style argument from within code, you must use Chr(34) to enclose the text (34 is the character code for a quotation mark (")).

Exercise Try using some of the above formats and placeholders

© Peter Bilbie – 2007-8 Page 9 of 16 Manipulating Date/Time data types The Date data type is used to store dates and times and there are various functions, methods and properties that we can use for date and time manipulation. There are a number of ways in which you can assign dates to variables and VB .NET will implicitly convert strings to dates, but only if Option Strict is turned off.

Exercise Create a new form – FrmDates – and add six textboxes – txtDate1 etc – and a button. Don’t forget to add a menu item in you MDI project

Below are several examples of how to create and assign date values. Using the form you have just created, add the following code to the click event of the button:

Dim aDate As Date 'Use the hash character to assign a date directly to a variable 'returns American format aDate = #1/8/2007# txtDate1.Text = aDate

'Implictly converts to a short date aDate = "1 August 2007" txtDate2.Text = aDate

'Using speech marks always returns date in short date format ' whatever date format input 'aDate = "22/2/2007" ' aDate = "6 Jun 2007" ‘aDate = "June 6 2007"

'shows current date and time txtDate3.Text = Date.Now

'shows current date txtDate4.Text = Date.Today

'creates a new date using the constructor of the Date class ‘parameters in Year, Month, Day format Dim aNewDate As New Date(2007, 8, 1)

txtDate5.Text = aNewDate.ToShortDateString

'long dates either way 'txtDate6.Text = Convert.ToDateTime("November 14 2007") txtDate6.Text = Convert.ToDateTime("14 November 2007")

© Peter Bilbie – 2007-8 Page 10 of 16 The result is shown below:

Formatting Dates We can use the Format and convert functions or the methods available to date variables to format dates. Edit out the code that you have placed in the buttons event procedure and add the following – read the comments for information:

'------'We have to give the variable the American format ‘when using the # separator 'but we can force the day, month, year format as below

aDate = #8/1/2007# txtDate1.Text = Format(aDate, "dd/MM/yyyy")

‘Formats the string as Date time but as VB has implicitly ‘converted the string. It is redundant unless we are adding the data to a database where it is expecting a date type aDate = "22/2/2007" txtDate2.Text = Convert.ToDateTime(aDate)

'using the aDate variables methods to set the date format txtDate3.Text = aDate.ToLongDateString txtDate4.Text = aDate.ToShortDateString txtDate5.Text = aDate.ToString("dd MMMM yyyy")

'Time formats - Today time returns 00:00 'Now returns current time 'txtDate6.Text = Date.Today.ToShortTimeString txtDate6.Text = Date.Now.ToShortTimeString

Exercise Try out some of the other date and time functions and methods to see what they do – use the lists below to help – courtesy of MS help files (again)

© Peter Bilbie – 2007-8 Page 11 of 16 Date and time formats You can also use the following formats for data and time values

Format Name Description General Date, or Displays a date and/or time. For real numbers, display a date and G time; for example, 4/3/93 05:34 PM.If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by your system's LocaleID value. Long Date, or D Displays a date according to your locale's long date format. Medium Date Displays a date using the medium date format appropriate for the language version of the host application. Short Date, or d Displays a date using your locale's short date format. Long Time, or T Displays a time using your locale's long time format; includes hours, minutes, seconds. Medium Time Displays time in 12-hour format using hours and minutes and the AM/PM designator. Short Time, or t Displays a time using the 24-hour format, for example, 17:45. f Displays the long date and short time according to your locale's format. F Displays the long date and long time according to your locale's format. g Displays the short date and short time according to your locale's format. M, m Displays the month and the day of a date. R, r Formats the date and time as Greenwich Mean Time (GMT) s Formats the date and time as a sortable index. u Formats the date and time as a GMT sortable index. U Formats the date and time with the long date and long time as GMT. Y, y Formats the date as the year and month.

© Peter Bilbie – 2007-8 Page 12 of 16 Date and Time placeholders

Character Description (:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system's LocaleID value. (/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your locale. (%) Used to indicate that the following character should be read as a single-letter format without regard to any trailing letters. Also used to indicate that a single-letter format is read as a user-defined format. See below for further details d Displays the day as a number without a leading zero (for example, 1). Use %d if this is the only character in your user-defined numeric format. dd Displays the day as a number with a leading zero (for example, 01). ddd Displays the day as an abbreviation (for example, Sun). dddd Displays the day as a full name (for example, Sunday). M Displays the month as a number without a leading zero (for example, January is represented as 1). Use %M if this is the only character in your user-defined numeric format. MM Displays the month as a number with a leading zero (for example, 01/12/01). MMM Displays the month as an abbreviation (for example, Jan). MMMM Displays the month as a full month name (for example, January). gg Displays the period/era string (for example, A.D.) h Displays the hour as a number without leading zeros using the 12-hour clock (for example, 1:15:15 PM). Use %h if this is the only character in your user-defined numeric format. hh Displays the hour as a number with leading zeros using the 12-hour clock (for example, 01:15:15 PM). H Displays the hour as a number without leading zeros using the 24-hour clock (for example, 1:15:15). Use %H if this is the only character in your user-defined numeric format. HH Displays the hour as a number with leading zeros using the 24-hour clock (for example, 01:15:15). m Displays the minute as a number without leading zeros (for example, 12:1:15). Use %m if this is the only character in your user-defined numeric format. mm Displays the minute as a number with leading zeros (for example, 12:01:15). s Displays the second as a number without leading zeros (for example, 12:15:5). Use %s if this is the only character in your user-defined numeric format.

© Peter Bilbie – 2007-8 Page 13 of 16 Character Description ss Displays the second as a number with leading zeros (for example, 12:15:05). F Displays fractions of seconds. For example ff will display hundredths of seconds, whereas ffff will display ten-thousandths of seconds. You may use up to seven f symbols in your user-defined format. Use %f if this is the only character in your user-defined numeric format. T Uses the 12-hour clock and displays an uppercase A for any hour before noon; displays an uppercase P for any hour between noon and 11:59 P.M. Use %t if this is the only character in your user-defined numeric format. tt Uses the 12-hour clock and displays an uppercase AM with any hour before noon; displays an uppercase PM with any hour between noon and 11:59 P.M. y Displays the year number (0-9) without leading zeros. Use %y if this is the only character in your user-defined numeric format. yy Displays the year in two-digit numeric format with a leading zero, if applicable. yyy Displays the year in four digit numeric format. yyyy Displays the year in four digit numeric format. z Displays the timezone offset without a leading zero (for example, -8). Use %z if this is the only character in your user-defined numeric format. zz Displays the timezone offset with a leading zero (for example, -08) zzz Displays the full timezone offset (for example, -08:00)

Working with Date/Time Parts and Intervals When working with time and date variables, it is sometimes necessary to parse out only the date or time part that we need i.e. day, month, minute, hour etc. A date object (variable) has many properties and methods that will allow us to do this. To access these properties and methods, after the object (variable) name add a period and the list will be displayed i.e.

Method

Property

© Peter Bilbie – 2007-8 Page 14 of 16 Edit out the code and type in the following code – read the comments:

'Date properties aDate = Convert.ToDateTime("1/08/2006") txtDate1.Text = aDate.DayOfWeek txtDate2.Text = aDate.Month txtDate3.Text = aDate.Year

'Date methods

'Adds days to date object txtDate4.Text = aDate.AddDays(30) 'txtDate5.Text = aDate.IsLeapYear(2000)

'Other Functions

'Leap year - another way If Date.IsLeapYear(aDate.Year) Then txtDate5.Text = "Leap Year" Else txtDate5.Text = "Not Leap Year" End If

'DateDiff - takes 3 parameters, the count ie days, months 'a date from and a date to txtDate6.Text = DateDiff(DateInterval.Day, aDate, Date.Today)

Comparing Dates It is possible to compare dates, for example we could check if one date is greater than the other – see code below:

Dim aDate As Date = Convert.ToDateTime(txtDate1.Text) Dim aDate2 As Date = Convert.ToDateTime(txtDate2.Text)

If aDate > aDate2 Then MessageBox.Show("1st Date is Greater than 2nd Date", "Date", _ MessageBoxButtons.OK, MessageBoxIcon.Information) Else MessageBox.Show("2nd Date is Greater than 1st Date", "Date", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End If

However, if we put the same dates in, which one is greater?

Exercise

© Peter Bilbie – 2007-8 Page 15 of 16 Try writing the code to check if they are the same and display a suitable message. Hint - Have a look the Date function Date.Compare(aDate, aDate2) Summary This session covered formatting and manipulation of numeric and Date data types. Topics covered were:  Whole ad fractional numbers  Number conversions  Casting  Option strict  Widening and narrowing  Numeric formats  ToString Function  User defined formats – placeholders  Manipulating Dates and times  Formatting dates  Date functions – date comparisons and calculations

Next session we will be covering arrays

© Peter Bilbie – 2007-8 Page 16 of 16

Recommended publications