How to use Mathematical functions, Type Conversion functions, and String functions in Visual Basic .NET or in Visual Basic 2005

Summary

This step-by-step article describes how to use Mathematical functions, Type Conversion functions, and String functions that are defined in Visual Basic .NET or Visual Basic 2005.

back to the top

Use Math Functions

The functions that are used for mathematical calculations are defined in the System.Math class. The Math class includes trigonometric functions, logarithmic functions, and other common mathematical functions. The following functions are the functions that are defined in the Math class of the System namespace.

Note To use these functions, import the System.Math namespace to your project by adding the following code to the top of the source code:
Imports System.Math
Abs

The Abs function returns the absolute value of the specified number.

Abs example:

This example uses the Abs method of the Math class to compute the absolute value of a number.
' Code will not compile unless it is put in a Sub or in a Function.
Dim MyNumber As Double
MyNumber = Abs(50.3) ' Returns 50.3.
MyNumber = Abs(-50.3) ' Returns 50.3.
Atan

The Atan function returns a Double value that contains the angle. The tangent of the angle is the specified number. A positive return value represents a counter-clockwise angle from the x-axis. A negative return value represents a clockwise angle. Multiply the return value by 180 divided by pi (π) to convert from radians to degrees.

Atan example:

This example uses the Atan method of the Math class to calculate the value of pi.
' Code is not compiled unless it is put in a Sub or in a Function.
Dim pi As Double
pi = 4 * Atan(1) ' Calculate the value of pi.
Cos

The Cos function takes an angle in radians as an argument and then returns a Double value that is the cosine of the specified angle.

Cos example:

This example uses the Cos method of the Math class to return the cosine of an angle.
' Code is not compiled unless it is put in a Sub or in a Function.
Dim MyAngle, MySecant As Double
MyAngle = 1.3 ' Define angle in radians.
MySecant = 1 / Cos(MyAngle) ' Calculate secant.
Exp

The Exp function returns a Double value that contains e (the base of natural logarithms) raised to the specified power. Use the Pow method to calculate powers of other bases. Exp is the inverse of Log.

Exp example:

This example uses the Exp method of the Math class to return e raised to a power.
' Code is not compiled unless it is put in a Sub or in a Function.
Dim MyAngle, MyHSin As Double
' Define angle in radians.
MyAngle = 1.3
' Calculate hyperbolic sine.
MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2
Log

The Log function returns a Double value that contains the logarithm of a specified number. This method is overloaded and can return either the natural (base e) logarithm of a specified number or the logarithm of a specified number in a specified base.

Log example:

This example uses the Log method of the Math class to return the natural logarithm of a number.
' Code is not compiled unless it is put in a Sub or in a Function.
Dim MyAngle, MyLog As Double
' Define angle in radians.
MyAngle = 1.3
' Calculate inverse hyperbolic sine.
MyLog = Log(MyAngle + Sqrt(MyAngle * MyAngle + 1))
Round

The Round function returns a Double value that contains the number that is nearest the specified value. Additional Round functions are available as methods of the intrinsic types such as the Decimal.Round method.

Round example:

This example uses the Round method of the Math class to round a number to the nearest integer.
' Code is not compiled unless it is put in a Sub or in a Function.
Dim MyVar1 As Double = 2.8
Dim MyVar2 As Double
MyVar2 =Round(MyVar1) ' Returns 3.
Sign

The Sign function returns an integer value that indicates the sign of a number. The following table shows the input arguments of the function and of the return values:
Specified NumberReturn Value
Positive1
Negative-1
Zero0

Sign example:

This example uses the Sign method of the
Math class to determine the sign of a number.
' Code is not compiled unless it is put in a Sub or in a Function.
Dim MyVar1, MyVar2, MyVar3 As Double
Dim MySign As Integer
MyVar1 = 12
MyVar2 = -2.4
MyVar3 = 0
MySign = Sign(MyVar1) ' Returns 1.
MySign = Sign(MyVar2) ' Returns -1.
MySign = Sign(MyVar3) ' Returns 0.
Sin

The Sin function takes an angle in radians as an argument and then returns a Double value that specifies the sine of the angle.

Sin example:

This example uses the Sin method of the Math class to return the sine of an angle.
' Code is not compiled unless it is put in a Sub or in a Function.
Dim MyAngle, MyCosecant As Double
MyAngle = 1.3 ' Define angle in radians.
MyCosecant = 1 / Sin(MyAngle) ' Calculate cosecant.
Sqrt

The Sqrt function returns a Double value that specifies the square root of the specified number.

Sqrt example:

This example uses the Sqrt method of the Math class to calculate the square root of a number.
' Code is not compiled unless it is put in a Sub or in a Function.
Dim MySqr As Double
MySqr = Sqrt(4) ' Returns 2.
MySqr = Sqrt(23) ' Returns 4.79583152331272.
MySqr = Sqrt(0) ' Returns 0.
MySqr = Sqrt(-4) ' Returns NaN (not a number).
Tan

The Tan function returns a Double value that contains the tangent of the specified angle. The Tan function takes an angle that is measured in radians as the argument. When the angle that is specified is NaN, NegativeInfinity, or PositiveInfinity, this method returns NaN.

Note Multiply by π/180 to convert degrees to radians.

Tan example:

This example uses the Tan method of the Math class to return the tangent of an angle.
' Code is not compiled unless it is put in a Sub or in a Function.
Dim MyAngle, MyCotangent As Double
MyAngle = 1.3 ' Define angle in radians.
MyCotangent = 1 / Tan(MyAngle) ' Calculate cotangent.
back to the top

Use Type Conversion Functions

The process of changing a value from one data type to another data type is named conversion. Conversions are either widening or narrowing, depending on the data capacities of the types that are involved. Widening conversion and narrowing conversion are both supported by the common language runtime. For example, the value that is represented as a 32-bit signed integer can be converted to a 64-bit signed integer. This is an example of a widening conversion. The opposite conversion (from 64-bit to 32-bit) is an example of a narrowing conversion. Information is never lost as a result of a widening conversion. However, information may be lost as a result of a narrowing conversion.

The following Type Conversion functions are defined in Visual Basic .NET or in Visual Basic 2005:

CBool

The CBool function is used to convert string expressions or numeric expressions to Boolean values. When an expression evaluates to a non-zero value, then the CBool function returns True. Otherwise, the function returns False.

CBool example:
Dim A, B, C As Integer
Dim Check As Boolean
A = 5
B = 5
Check = CBool(A = B) ' Check is set to True.
C = 0
Check = CBool(C) ' Check is set to False.
CByte

The CByte function converts a specified number to a byte. The input argument must be a number between 0 and 255. Otherwise, you receive a System.OverflowException.

CByte example:
Dim MyDouble As Double
Dim MyByte As Byte
MyDouble = 125.5678
MyByte = CByte(MyDouble) ' MyByte is set to 126.
CChar

The CChar function converts only the first character of the specified String. The input argument to CChar must be a data-type string. You cannot use CChar to convert a number to a character because CChar cannot accept a numeric data type.

CChar example:

This example uses the
CChar function to convert the first character of a string expression to a Char type.
Dim MyString As String
Dim MyChar As Char
MyString = "BCD" ' CChar converts only the first character of the string.
MyChar = CChar(MyString) ' MyChar is set to "B".
CDate

CDate accepts any valid representation of a date and a time and then converts to a Date.

CDate example:

This example uses the
CDate function to convert strings to Date values.
Dim MyDateString, MyTimeString As String
Dim MyDate, MyTime As Date
MyDateString = "February 12, 1969"
MyTimeString = "4:35:47 PM"
' ...
MyDate = CDate(MyDateString) ' Convert to Date data type.
MyTime = CDate(MyTimeString) ' Convert to Date data type.
CDbl

The CDbl function is used to convert a numeric expression to a Double value. The input argument of the function must be between -4.94065645841247E-324 and -1.79769313486231E+308 for negative values. The input argument of the function must be between 1.79769313486231E+308 and 4.94065645841247E-324 for positive values.

CDbl example:
Dim MyDec As Decimal
Dim MyDouble As Double
MyDec = 234.456784D ' Literal type character D makes MyDec a Decimal.
MyDouble = CDbl(MyDec * 8.2D * 0.01D) ' Convert result to a Double.
CDec

The CDec function converts a numeric value to a decimal.


CDec example:
Dim MyDouble As Double
Dim MyDecimal As Decimal
MyDouble = 10000000.0587
MyDecimal = CDec(MyDouble) ' Convert to Decimal.
CInt

The CInt function converts a numeric value to an integer.


CInt example:
Dim MyDouble As Double
Dim MyInt As Integer
MyDouble = 2345.5678
MyInt = CInt(MyDouble) ' MyInt is set to 2346.
CLng

The CLng function takes a numeric value as an argument and then returns a Long value.

CLng example:
Dim MyDbl1, MyDbl2 As Double
Dim MyLong1, MyLong2 As Long
MyDbl1 = 25427.45
MyDbl2 = 25427.55
MyLong1 = CLng(MyDbl1) ' MyLong1 contains 25427.
MyLong2 = CLng(MyDbl2) ' MyLong2 contains 25428.
CObj

The CObj function converts a numeric value to an Object.


CObj example:
Dim MyDouble As Double
Dim MyObject As Object
MyDouble = 2.7182818284
MyObject = CObj(MyDouble) ' Double value is pointed to by MyObject.
CShort

The CShort function converts a numeric value to Short.

CShort example:
Dim MyByte as Byte
Dim MyShort as Short
MyByte = 100
MyShort = CShort(MyByte) ' Convert to Short.
CSng

The CSng function converts the numeric value to Single.


CSng example:
Dim MyDouble1, MyDouble2 As Double
Dim MySingle1, MySingle2 As Single
MyDouble1 = 75.3421105
MyDouble2 = 75.3421567
MySingle1 = CSng(MyDouble1) ' MySingle1 is set to 75.34211.
MySingle2 = CSng(MyDouble2) ' MySingle2 is set to 75.34216.
CStr

The following table shows the input arguments and the return values of the CStr function:
Input Argument Data TypeReturn Value
BooleanA string that contains True or False
DateA string that contains a Date value (date and time) in the short date format of your system
Numeric ValueA string that represents the number

CStr example:

This example uses the CStr function to convert a numeric value to a string.
Dim MyDouble As Double
Dim MyString As String
MyDouble = 437.324
MyString = CStr(MyDouble) ' MyString is set to "437.324".
back to the top

Use String Functions

The String functions are defined in different classes. The classes include the Microsoft.VisualBasic.Strings class and the System.String class.

back to the top

Use String Functions in the Microsoft.VisualBasic.Strings Class

The following functions are the String functions that are defined in the
Microsoft.VisualBasic.Strings class.

Note To use the String functions, import the namespace Microsoft.VisualBasic.Strings to your project by adding the following code at the beginning of the source code:
Imports Microsoft.VisualBasic.Strings
Asc and AscW

The Asc function and the AscW function return an integer value that represents the character code that corresponds to the specified character. The functions accept any valid Char expression or String expression as an argument. When a string is the input argument, only the first character of the string is used for input. When the string contains no characters, an ArgumentException error occurs.
Asc returns the code point or the character code for the input character. The return value can be between 0 and 255 for single-byte character set (SBCS) values. The return value can be between -32768 to 32767 for double-byte character set (DBCS) values.
AscW returns the Unicode code point for the input character that can be between 0 and 65535.

Example:
Dim MyInt As Integer
MyInt = Asc("A") ' MyInt is set to 65.
MyInt = Asc("a") ' MyInt is set to 97.
MyInt = Asc("Apple") ' MyInt is set to 65.
Chr and ChrW

The Chr function and the ChrW function return the character that is associated with the specified character code. When CharCode is outside the range of -32768 through 65535, then an ArgumentException error occurs.

Example:


This example uses the Chr function to return the character that is associated with the specified character code.
Dim MyChar As Char
MyChar = Chr(65) ' Returns "A".
MyChar = Chr(97) ' Returns "a".
MyChar = Chr(62) ' Returns ">".
MyChar = Chr(37) ' Returns "%".
GetChar

The GetChar function returns a Char value that represents the character from the specified index in the specified string. When the index is less than 1 or greater than the index of the last character in the specified input argument, an ArgumentException occurs.

Example:

This example shows how to use the
GetChar function to return a character from a specified index in a string.
Dim myString As String = "ABCDE"
Dim myChar As Char
myChar = GetChar(myString, 4) ' myChar = "D"
InStr

The InStr function returns an integer that specifies the start position of the first occurrence of one string that is in another string.

Example:

The following example uses the InStr function to return the position of the first occurrence of one string that is in another string:
Dim SearchString, SearchChar As String
Dim MyPos As Integer
SearchString ="XXpXXpXXPXXP" ' String to search in.
SearchChar = "P" ' Search for "P".
' A textual comparison starting at position 4. Returns 6.
MyPos = InStr(4, SearchString, SearchChar, CompareMethod.Text)
Join

The Join function returns a string that is created by joining substrings that are contained in an array. The one-dimensional array that contains substrings that must be joined is passed as an argument to the Join function. The function uses Delimiter, String to separate the substrings in the returned strings as an optional argument. When the Delimiter is omitted, the space character (" ") is used as the separator between the substrings. When the Delimiter is a zero-length string (""), the substrings in the array are concatenated with no separators.

Example:

The following example shows how to use the Join function:
Dim myItem(2) As String
Dim myShoppingList As String
myItem(0) = "Pickle"
myItem(1) = "Pineapple"
myItem(2) = "Papaya"
' Returns "Pickle, Pineapple, Papaya"
myShoppingList = Join(myItem, ", ")
LCase

The LCase function returns a string or a character that has been converted to lowercase. Only uppercase letters are converted to lowercase. All lowercase letters and non-letter characters remain unchanged.

Example:

The following example uses the LCase function to return a lowercase version of a string:
Dim UpperCase, LowerCase As String
Uppercase = "Hello WORLD 1234" ' String to convert.
Lowercase = LCase(UpperCase) ' Returns "hello world 1234".
LTrim, RTrim, and Trim

These functions return a string that contains a copy of a specified string. When you use LTrim, there are no leading spaces. When you use RTrim, there are no trailing spaces. When you use Trim, there are no leading spaces and no trailing spaces.

Example:

The following example uses the LTrim function to remove leading spaces, the RTrim function to remove trailing spaces, and the Trim function to remove both leading spaces and trailing spaces from a String variable:
Dim MyString, TrimString As String
MyString = " <-Trim-> " ' Initializes string.
TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ".
TrimString = RTrim(MyString) ' TrimString = " <-Trim->".
TrimString = LTrim(RTrim(MyString)) ' TrimString = "<-Trim->".
' Using the Trim function alone achieves the same result.
TrimString = Trim(MyString) ' TrimString = "<-Trim->".
Replace

The Replace function returns a string where a specified substring is replaced with another substring a specified number of times. The return value of the Replace function is a string that begins at the position that is specified by the Start argument and then concludes at the end of the specified string with the substitutions made as specified by the values in the Find argument and the Replace argument.

Example:

This example demonstrates the Replace function:
Dim myString As String = "Shopping List"
Dim aString As String
' Returns "Shipping List".
aString = Replace(myString, "o", "i")
StrComp

The StrComp function returns -1, 0, or 1. This is based on the result of a string comparison. The strings are compared by alphanumeric sort values beginning with the first character.

Example:

The following example uses the StrComp function to return the results of a string comparison. When the third argument is omitted, the comparison type that is defined in the option compare statement or the project defaults is used.
Dim MyStr1, MyStr2 As String
Dim MyComp As Integer
MyStr1 = "ABCD"
MyStr2 = "abcd" ' Defines variables.
' The two strings sort equally. Returns 0.
MyComp = StrComp(MyStr1, MyStr2, CompareMethod.Text)
' MyStr1 sorts after MyStr2. Returns -1.
MyComp = StrComp(MyStr1, MyStr2, CompareMethod.Binary)
' MyStr2 sorts before MyStr1. Returns 1.
MyComp = StrComp(MyStr2, MyStr1)
StrConv

The StrConv function returns a string that is converted as specified in the input arguments. The StrConv function converts the string. The conversion is based on the value in the
Conversion argument. The value in the Conversion argument is a member of VbStrConv enumeration.

The Conversion argument settings are:
Enumeration MemberDescription
VbStrConv.NonePerforms no conversion
VbStrConv.LinguisticCasing-Uses linguistic rules for casing instead of File System (default)
-Valid with UpperCase and LowerCase only
VbStrConv.UpperCaseConverts the string to uppercase characters
VbStrConv.LowerCaseConverts the string to lowercase characters
VbStrConv.ProperCaseConverts the first letter of every word in the string to uppercase

Example:

The following example converts text to lowercase letters:
Dim sText, sNewText As String
sText = "Hello World"
sNewText = StrConv(sText, VbStrConv.LowerCase)
Debug.WriteLine (sNewText) ' Outputs "hello world".
StrDup

The StrDup function returns a string or an object that is made up of the specified character that is repeated the specified number of times. The StrDup function takes two arguments, the Number argument and the Character argument. The Number argument specifies the length to the string that must be returned by the function. The StrDup function uses only the first character in the Character argument. The Character argument can be a Char data type, a String data type, or an Object data type.

Example:

The following example uses the StrDup function to return a string of duplicated characters:
Dim aString As String = "Wow! What a string!"
Dim aObject As New Object()
Dim myString As String
aObject = "This is a String that is contained in an Object"
myString = StrDup(5, "P") ' Returns "PPPPP"
myString = StrDup(10, aString) ' Returns "WWWWWWWWWW"
myString = StrDup(6, aObject) ' Returns "TTTTTT"
StrReverse

The StrReverse function returns a string that has the character order of a specified string reversed.

Example:
Dim myString As String = "ABCDEFG"
Dim revString As String
' Returns "GFEDCBA".
revString = StrReverse(myString)
UCase

The UCase function returns a string or a character that contains the specified string that is converted to uppercase. Only lowercase letters are converted to uppercase letters. All uppercase letters and non-letter characters remain unchanged.

Example:

The following example uses the UCase function to return an uppercase version of a string:
Dim LowerCase, UpperCase As String
LowerCase = "Hello World 1234" ' String to convert.
UpperCase = UCase(LowerCase) ' Returns "HELLO WORLD 1234".
back to the top

Use String Functions in the System.String Class

The following are the String functions in the String class of the System Namespace.

Note To use the String functions, import the System.String namespace to your project by adding the following code to the beginning of the source code:
Imports System.String
Compare

The Compare function compares two strings that are in the input arguments. The comparison is performed by using word sort rules. The comparison terminates when an inequality is discovered or both strings are compared.

Compare example:
' Code is not compiled unless it is put in a Sub or in a Function.
Dim s1, s2 As String
s1 = "testexample"
s2 = "testex"
MsgBox(Compare(s2, s1)) 'Returns -1.
MsgBox(Compare(s1, s2)) 'Returns 1.
Concat

The Concat function concatenates one or more strings and then returns the concatenated string.

Concat example:

The following example shows how to use overloaded versions of Concat:
' Code is not compiled unless it is put in a Sub or in a Function.
Dim s1, s2, sa(3) As String
sa(0) = "A"
sa(1) = "B"
sa(2) = "C"
s1 = "test"
s2 = "example"
s1 = Concat(s1, s2) 'Returns testexample.
MsgBox(s1)
MsgBox(Concat(sa)) 'Returns ABC.
Copy

The Copy function copies the value that is in the specified string to another string.

Copy example:
' Code is not compiled unless it is put in a Sub or in a Function.
Dim s1, s2 As String
s1 = "Hello World"
'Copy the string s1 to s2.
s2 = Copy(s1)
MsgBox(s2) 'Displays Hello World.
Remove

The Remove function deletes a specified number of characters from the specified string beginning at a specified position. The Remove function has two parameters. They are the StartIndex parameter and the Count parameter. The Startindex parameter is the position in the string that specifies where to start deleting characters. The Count parameter specifies the number of characters to delete.

Remove example:
' Code is not compiled unless it is put in a Sub or in a Function.
Dim s1, s2 As String
s1 = "Hello World"
'Removes 3 characters starting from character e.
s2 = s1.Remove(1, 3)
MsgBox(s2) 'Displays Ho World.

Substring

The Substring function retrieves a string starting at the specified position in the specified string.

Substring example:

The following example retrieves a substring starting at a specified character position and with a specified length:
' Code is not compiled unless it is put in a Sub or in a Function.
Dim s1, s2 As String
s1 = "Hello World"
s2 = s1.Substring(6, 5) 'Returns World.
MsgBox(s2) 'Displays World.
ToCharArray

The ToCharArray function copies the characters in the string to a Unicode character array.

ToCharArray example:

The following example copies characters at a specified position to a Character array:
 ' Code is not compiled unless it is put in a Sub or in a Function.
Dim s1 As String
Dim ch(10) As Char
s1 = "Hello World"
'Copies the characters starting from W to d to a Character array.
ch = s1.ToCharArray(6, 5)
MsgBox(ch(3)) 'Displays l.
ToLower

The ToLower function takes a string argument and then returns a copy of this string in lowercase.

ToLower example:
' Code is not compiled unless it is put in a Sub or in a Function.
Dim s1, s2 As String
s1 = "Hello World"
s2 = s1.ToLower() 'Converts any uppercase characters to lowercase.
MsgBox(s2) 'Displays hello world.
ToUpper

The ToUpper function takes a string argument and then returns a copy of this string in uppercase.

ToUpper example:
' Code is not compiled unless it is put in a Sub or in a Function.
Dim s1, s2 As String
s1 = "Hello World"
s2 = s1.ToUpper() 'Converts any lowercase characters to uppercase.
MsgBox(s2) 'Displays HELLO WORLD.
Trim, TrimStart, and TrimEnd

These functions return a string that contains a copy of a specified string. When you use the Trim function, there are no leading spaces and no trailing spaces. When you use the TrimStart function, there are no leading spaces. When you use the TrimEnd function, there are no trailing spaces.

Example:

The following example uses the TrimStart function to remove spaces at the beginning, the TrimEnd function to remove spaces at the end, and the Trim function to remove both leading spaces and trailing spaces from a String variable:
' Code is not compiled unless it is put in a Sub or in a Function.
Dim s1, s2 As String
s1 = " Hello World "
s2 = s1.Trim() 'Returns Hello World without any white spaces.
s2 = s1.TrimStart 'Removes the spaces at the start.
s2 = s1.TrimEnd 'Removes the white spaces at the end.

back to the top

References

For more information about functions, visit the following Microsoft Web site:

http://msdn2.microsoft.com/en-us/library/32s6akha(vs.71).aspx

back to the top
Propriedades

ID do Artigo: 818805 - Última Revisão: 26 de nov de 2007 - Revisão: 1

Comentários