VB FUNCTIONS AND OPERATORS In der to compute inputs from users and generate results, we need to use various mathematical operats. In Visual Basic, other than the addition (+) and subtraction (-), the symbols f the operats are different from nmal mathematical operats, as shown in the table below: OPERATOR MATHEMATICAL FUNCTION EXAMPLE ^ Exponents 2 ^ 4 = 16 * Multiplication 4 * 3 = 12 / Division 12 / 4 = 3 + Addition 7 + 5 = 12 - Subtraction 7 5 = 2 Mod Modulus (returns the remainder from an integer division) 15 Mod 4 = 3 \ Integer Division (discards the decimal places) 19 \ 4 = 4 + & String concatenation ICS & 2O1 = ICS2O1 ORDER OF OPERATIONS Visual Basic evaluates a numeric expression using a specific der of operations, operat precedence. The following table outlines the der of operations used in Visual Basic: ORDER OPERATOR FUNCTION 1 st ^ Exponents 2 nd +, - Unary 3 rd *, / Multiplication and Division 4 th \ Integer Division 5 th Mod Modulus 6 th +, - Addition and Subtraction VB Functions and Operats Page 1 of 11
Operat precedence can, of course, be changed by including parentheses in a numeric expression. The operations within parentheses are evaluated first. COMBINED ASSIGNMENT OPERATORS Sometimes you might find it necessary to change the value of a variable by doubling it subtracting a certain amount from it while keeping the result in the variable itself. Combined assignment operats (sometimes called compound operats) are designed to do just that. Without compound operats, you would have to type the variable name twice once f the left ption of the equation and again in the right ption of the equation. The following table outlines the compound operats available in Visual Basic: COMPOUND OPERATOR EXAMPLE EQUIVALENT += x += 5 x = x + 5 -= x -= 5 x = x - 5 *= x *= 5 x = x * 5 /= x /= 5 x = x / 5 \= x \= 5 x = x \ 5 &= name &= lastname name = name & lastname VB Functions and Operats Page 2 of 11
IMPLICIT TYPE CONVERSION When you assign a value to one date type to a variable of another data type, Visual Basic attempts to convert the value being assigned to the data type of the receiving variable. This is known as implicit type conversion. F example, let s say we want to assign the integer 5 to a variable of type Single named num: Dim num As Single = 5 When the statement executes, the integer 5 is automatically converted into the real number 5.0, which is then sted in the variable num. This conversion is what s called a widening conversion because no data is lost. NARROWING CONVERSIONS If you assign a real number to an integer variable, Visual Basic attempts to perfm what s called a narrowing conversion. Oftentimes, some data is lost. F example, the following statement assigns 12.2 to an integer variable: Dim num As Integer = 12.2 The value 12.2 is rounded down to 12. Similarly, the next statement rounds up to the nearest integer (i.e. 13) when the fractional part of the number is greater than.5: Dim num As Integer = 12.6 Another narrowing conversion occurs when assigning a Double value to a variable type Single. Both hold floating-point values, but Double permits me significant digits: Dim numone As Double = 1.2345678 Dim numtwo As Single = numone The value sted in numtwo is rounded up to 1.234568 because variables of Single type can only hold seven significant digits. CONVERTING STRINGS TO NUMBERS Under some circumstances, Visual Basic will try to convert string values to numbers. In the following statement, f example, 12.2 is a string containing a numeric expression: Dim num As String = 12.2 VB Functions and Operats Page 3 of 11
The string 12.2 is a string of characters in a numeric-like fmat that cannot be used f calculations. When the following statements execute, the string 12.2 is converted to the number 12.2: Dim num As Single num = 12.2 If we assign the string 12.2 to an Integer variable, the result is rounded down to 12: Dim num As Integer num = 12.2 A similar effect occurs when the user enters a number into a TextBox control. We usually want to assign the contents of the text box s Text property to a numeric value. The Text property is by definition type String, so its contents are implicitly converted to a number when we assign it to a numeric variable: Dim num As Integer num = txtvalue.text OPTION STRICT Visual Basic has a configuration option named Option Strict that determines whether certain implicit conversions are legal. If you set Option Strict to ON, only widening conversions are permitted (such as Integer to Single). The following diagram shows how implicit conversion between numeric types must be in a left-to-right direction: Byte Integer Long Decimal Single Double A Single value can be assigned to a variable of type Double, an Integer can be assigned to a variable of type Single, etc. If, on the other hand, Option Strict is set to OFF, all types of numeric conversions are permitted, with possible loss of data. Option Strict can be set in two different ways: 1. By inserting an Option Strict statement at the top of the source code file: Option Strict On 2. Right-click the project name in the Solution Expler window, select Properties, and then select the Compile tab. From the Option Strict drop-down list, you can select ON OFF. VB Functions and Operats Page 4 of 11
Click COMPILE Click ON OFF It is recommended that you use Option Strict to catch errs that result when you accidentally assign a value of the wrong type to a variable. When set to ON, Option Strict fces you to use a conversion function, making your intentions clear, and helps to avoid runtime errs. EXPLICIT TYPE CONVERSIONS The following table outlines the most commonly used Visual Basic conversion functions. The input to each of the conversion functions is an expression, which is another name f a variable name, an arithmetic expression, etc. These conversion functions are required when Option Strict is set to ON and you need to assign a wider numeric type to a narrower numeric type (e.g. Long to Integer, Double to Single, etc.) FUNCTION CChar(expr) Convert.ToChar(expr) CBool(expr) Convert.ToBoolean(expr) CDbl(expr) Convert.ToDouble(expr) CInt(expr) Convert.ToInt32(expr) CLng(expr) Convert.ToInt64(expr) DESCRIPTION Converts a string expression to a Char. If the string contains me than one character, only the first character is returned. Converts a string expression (that must equal True False) to a Boolean. If the expression does not equal True, False Nothing, a runtime err is generated. Converts a numeric string expression to a Double. If the expression converts to a value outside the range of a Double, is not a numeric value, a runtime err is generated. Converts a numeric string expression to an Integer. If the expression converts to a value outside the range of an Integer, is not a numeric value, a runtime err is generated. Converts a numeric string expression to a Long. If the expression converts to a value outside the range of a Long, is not a numeric value, a runtime err is generated. CSng(expr) Converts a numeric string expression to a Single. VB Functions and Operats Page 5 of 11
Convert.ToSingle(expr) CStr(expr) Convert.ToString(expr) If the expression converts to a value outside the range of a Single, is not a numeric value, a runtime err is generated. Converts a numeric, Boolean, Date String expression to a String. THE ToString() METHOD Each Visual Basic data type has a ToString() method, which returns a string representation of the variable calling the method. You call the ToString() method using the following general fmat: VariableName.ToString() The following code segment shows an example of the method s use: Dim num As Integer = 123 lblnumber.text = num.tostring() VB Functions and Operats Page 6 of 11
Numbers may be fmatted in various ways f output. Visual Basic provides a number of fmatting functions that allow you to convert values to strings and fmat their appearances. THE FmatNumber FUNCTION By default the FmatNumber function fmats a number to two decimal places and includes commas. F example, the number 1999 would be fmatted as 1,999.00. The number 123456789.89712 would be fmatted as 123,456,789.90. The following code is an example of how the FmatNumber function is used: Dim num As Double num = 7823.279 lblmessage.text = FmatNumber(num) The last statement passes the variable num to the FmatNumber function and returns the string 7,823.28, which is assigned to the lblmessage.text property. The FmatNumber function takes an optional second argument, which specifies the number of decimal places. The following example fmats a variable called laptime to four (4) decimal places: lblmessage.text = FmatNumber(lapTime, 4) THE FmatCurrency FUNCTION The FmatCurrency function fmats a number as currency (e.g. $5.85). The number is rounded to two (2) decimal places and includes commas as needed. The following is an example of how the FmatCurrency function is used: Dim totalcost As Double totalcost = 45123.9823 lbltotal.text = FmatCurrency(totalCost) The last statement passes the variable totalcost to the FmatCurrency function and returns the string $45,123.98, which is assigned to the lbltotal.text property. THE FmatPercent FUNCTION The FmatPercent function fmats a number as a percent by multiplying the argument by 100, rounding the result to two decimal places, and adding a percent symbol. The following is an example of how the FmatPercent function is used: VB Functions and Operats Page 7 of 11
Dim average As Double average = 0.56789 lblaverage.text = FmatPercent(average) The last statement passes the variable average to the FmatPercent function and returns the string 56.79%, which is assigned to the lblaverage.text property. Like FmatNumber and FmatCurrency, the FmatPercent function takes an optional second argument, which specifies the number of decimal places. The following example fmats the variable called average to zero (0) decimal places: lblaverage.text = FmatPercent(average, 0) VB Functions and Operats Page 8 of 11
Games, simulats, screen savers, and many other types of applications require random numbers. Visual Basic includes a Random class that generates a random number. In der to use the Random class, the first thing you need to do is create a new Random object as follows: 'Declare and initialize Random object Dim rnd As New Random The next thing you ll need to do is declare a variable that will ste the number that is randomly generated by the Random object that we created above: 'Declare and initialize variable to ste random number Dim randomnumber As Integer To generate a random number, we will need to use the Next() method included in the Random class which generates a positive integer value greater than equal to zero and less than 2,147,483,647. 'Generate and ste random number randomnumber = rnd.next() Let s now add a user interface to see how this program would wk. Create a fm and add a label and button as follows: lblnumber btngenerate Add the following code to the button: Private Sub btngenerate_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles btngenerate.click 'Declare and initialize Random object Dim rnd As New Random 'Declare and initialize variable to ste random number VB Functions and Operats Page 9 of 11
End Sub Dim randomnumber As Integer 'Randomly generate and ste random number randomnumber = rnd.next() 'Output and fmat the random number lblnumber.text = FmatNumber(randomNumber, 0,,, TriState.True) When you run the program, and click the GENERATE button, a random number is outputted in the label. SPECIFYING A RANGE OF NUMBERS We can specify a range of numbers by passing a single argument to the Next() method. F example, if I wanted to generate a random number between 0 and 5, I would use the Next() method as follows: randomnumber = rnd.next(6) When a single argument is passed to the Next() method, the values returned by Next() will be in the range from 0 to (but not including) the value of that argument. So, in the above example, the program will generate one of six possible numbers in the range 0-5. Let s say I wanted to generate a random number between 1 and 6. In this case, there are two ways we can do this. The first is simply pass a single argument to the Next() method to represent the amount of possible values the program will generate and simply add the minimum value to the equation, as follows: randomnumber = rnd.next(6) + 1 Alternatively, you can produce the same result by passing two arguments to the Next() method: the first representing the minimum value in our range and the second representing the maximum value + 1. randomnumber = rnd.next(1, 7) VB Functions and Operats Page 10 of 11
GENERATING FLOATING-POINT VALUES The Random() class includes a NextDouble() method to generate a random floating-point value greater than equal to 0 and less than 1. randomnumber = rnd.nextdouble() To specify a range of values, such as 1.0 10.0, we will need to multiply the result of NextDouble() by the amount of possible integer values - 1 (i.e. 10 1) and then add the minimum value, as follows: randomnumber = rnd.nextdouble() * 9 + 1 VB Functions and Operats Page 11 of 11