Home

Introduction to Visual Basic Built-In Functions

Fundamental Functions

Int/Fix

If you have a decimal number but are interested only in the integral part, to assist you with retrieving that part, the Visual Basic language provides the Int() and the Fix() functions. Their syntaxes are:

Public Shared Function Int( _
    ByVal Number As { Double | Integer | Long | 
		      Object | Short | Single | Decimal }) _
    As { Double | Integer | Long | Object | Short | Single | Decimal }
Public Shared Function Fix( _
    ByVal Number As { Double | Integer | Long | 
		      Object | Short | Single | Decimal }) _
    As { Double | Integer | Long | Object | Short | Single | Decimal }

Each function must take one argument. The value of the argument must be number-based. This means that it can be an integer or a floating-point number. If the value of the argument is integer-based, the function returns the (whole) number. If the value of the argument is a decimal number, the function returns only the integral part.

The Memory Used by a Data Type: Len

To let you get the amount of space that a data type or a variable uses or needs, the Visual Language provides the Len() function. Its syntax is:

Public Shared Function Len( _
   ByVal Expression As { Boolean | Byte | SByte | Char | Double |
   Integer | UInteger | Long | ULong | Object | Short | UShort |
   Single | String | DateTime | Decimal } _
) As Integer

To call this function, you can declare a variable with a data type of your choice and optionally initialize with the appropriate value, then pass that variable to the function.

Random Functions

To assist you with getting a random number, the Visual Basic language provides a function named Rnd. Its syntax is:

Public Shared Function Rnd[(Number)] As Single

This function takes an optional argument. If the argument is not passed, the compiler would simply generate a positive decimal number between 0 and 1.

If you call the function, every time you execute it, you are likely to get the same result. To assist you with seeding, the Visual Basic language provides a function named Randomize. Its syntax is:

Public Shared Sub Randomize ([ Number ])

This function takes one optional argument.

Conversions Functions

Introduction

As you may recall, each data type has a function used to convert a string value or an expression to that type. The general syntax of the conversion functions is:

return-type = function-name(expression)

The expression could be of any kind such as a string or an expression. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the return-type in our syntax.

The conversion functions are as follows:

Function Description
Name Return Type
CBool Boolean Converts an expression into a Boolean value
CByte Byte Converts an expression into Byte number
CDbl Double Converts an expression into a floating-point number with double precision
CDec Decimal Converts an expression into a decimal number
CInt Integer Converts an expression into an integer (natural) number
CLng Long Converts an expression into a long integer (a large natural) number
CObj Object Converts an expression into an Object type
CSByte SByte Converts an expression into a signed byte
CShort Short Converts an expression into a short integer
CSng Single Converts an expression into a floating-point number with single precision
CUInt UInt Converts an expression into an unsigned integer
CULng ULong Converts an expression into an unsigned long integer
CUShort UShort Converts an expression into an unsigned short integer

Type Conversion

Conversion functions allow you. Besides the conversion functions to convert a known value to another type, the Visual Basic language provides a function named CType. Its syntax is:

CType(expression, typename)

As you can see, the CType() function takes two arguments. The first argument is the expression or the value that you want to convert. An example could be the name of a variable or an expression. Here is an example:

CType(250.48 * 14.05, ...)

The second argument is the type of value you want to convert the first argument to. From what we have learned so far, this second argument can be one of the data types we have used. Here is an example:

CType(250.48 * 14.05, Single)

If you choose one of the data types, the expression produced by the first argument must be able to produce a value that is conform to the type of the second argument:

  • The conversion from the first argument to the type of the second argument must be possible: the value produced by the first must be convertible to the second argument. For example, if the first argument is an expression, the second argument must be a number-based data type. In the same way, you cannot convert a date to a number-based type
  • If the first argument is a number or the result of a calculation, its resulting value must be lower than or up to the range of values of the second argument
  • If the first argument is a number or the result of a calculation that produces an integer or a floating-point number, its resulting value must be convertible to an integer or a floating point number up to the range of values of the second argument
  • If the first argument is a number or the result of a calculation that produces an integer or a floating-point number, the second argument is a number-based data type but whose range cannot hold the resulting value of the first argument, the conversion would not be allowed (the conversion would fail)

After the CType() function has performed its conversion, it returns a value that is the same category as the second argument. If you try storing the returned value into a variable that cannot hold it, you would receive an error.

 
 
 

Numeric Formatting

Introduction

To let you appropriately display a value, the Visual Basic language provides a function named Format. This function can be used for different types of values The most basic technique consists of passing it an expression that holds the value to display. The syntax of this function is:

Public Shared Function Format( _
   ByVal Expression As Object, _
   Optional ByVal Style As String = "" _
) As String

The simplest way to use this function is to pass it a number, a string, or a date/time as the first argument. The function would then produce that number. Besides the Format() function, the Visual Basic language provides some additional functions we will review below.

To control how the number should display, you can pass the second argument of the Format() function. This argument would be passed as a string.

To produce the number in a general format, you can pass the second argument as "g", "G", "f", or "F". Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>
<script runat="server">
Sub Identify(ByVal Number As Long, ByVal FirstName As String,
             ByVal LastName As String, ByVal MiddleInitial As Char)
    Response.Write(CStr(Number) & ": " & FirstName & " " &
                        MiddleInitial & ". " & LastName )
End Sub

Function CalculateNetPay(ByVal HourlyRate As Double,
                         ByVal TotalTime As Double) As Double
    Return HourlyRate * TotalTime
End Function
</script>

<title>Employee Payroll</title>
</head>
<body>
<h3>Employee Payroll</h3>

<%
Dim HourlySalary = 24.2
Dim TimeWorked = 42.5
Dim Pay = CalculateNetPay(TotalTime := TimeWorked, HourlyRate := HourlySalary)

Response.Write("<b>Employee:</b> ")
Identify(FirstName := "Justine", LastName := "Gibbs",
         Number := 381751, MiddleInitial :=  "V"c)
Response.Write("<br><b>Hourly Salary:</b> " & Format(HourlySalary, "F"))
Response.Write("<br><b>Time Worked:</b> " & Format(TimeWorked, "F"))
Response.Write("<br><b>Net Pay:</b> " & Format(Pay, "f"))
%>

</body>
</html>

This would produce:

Numeric Formatting

To display the number with a decimal separator, pass the second argument as "n", "N", or "Standard". Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head run>
<style>
#container
{
    margin: auto;
    width:   225px;
}
#estimation {
    width:   230px;
}
</style>
<title>Salary Estimation</title>
</head>
<body>
<div id="container">

<%
Dim HourlySalary    = 24.2
Dim WeeklySalary   = HourlySalary * 40
Dim BiWeeklySalary = WeeklySalary  * 2
Dim MonthlySalary   = WeeklySalary * 4
Dim YearlySalary     = MonthlySalary * 12

Response.Write("<h2>Salary Estimation</h2>")
Response.Write("<table border=6 id='estimation'>")
Response.Write("<tr><td><b>Hourly Salary:</b></td><td>" & Format(HourlySalary, "N") & "</td></tr>")
Response.Write("<tr><td><b>Weekly Salary:</b></td><td>" & Format(WeeklySalary, "n") & "</td></tr>")
Response.Write("<tr><td><b>Bi-Weekly Salary:</b></td><td>" & Format(BiWeeklySalary, "n") & "</td></tr>")
Response.Write("<tr><td><b>Monthly Salary:</b></td><td>" & Format(MonthlySalary, "standard") & "</td></tr>")
Response.Write("<tr><td><b>Yearly Salary:</b></td><td>" & Format(YearlySalary, "STANDARD") & "</td></tr></table>")
%>

</div>
</body>
</html>

This would produce:

Numeric Formatting

Formatting a Number

An alternative to format a number is to use a function named FormatNumber. Its syntax is:

Function FormatNumber(
   ByVal Expression As Object,
   Optional ByVal NumDigitsAfterDecimal As Integer = -1,
   Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
   Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
   Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String

Only the first argument is required and it represents the value to display. If you pass only this argument, you get the same format as the Format() function called with the Standard option. If you call the Format() function with the Standard option, it would consider only the number of digits on the right side of the decimal separator. If you want to display more digits than the number actually has, call the FormatNumber() function and pass a second argument with the desired number. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>
<script Language="VB" runat="server">
Dim OriginalPrice# = 199.95

Function CalculateNetPrice#(Optional ByVal DiscountRate As Double = 20.00)
    Return OriginalPrice - (OriginalPrice * DiscountRate / 100.00)
End Function
</script>

<title>Department Store</title>
</head>
<body>
<h4>Department Store</h4>

<%
' Discount Rate = 35%
Dim Rate = 35.00

Dim FinalPrice# = 0.00

FinalPrice# = CalculateNetPrice(Rate)
Response.Write("Original Price = " & OriginalPrice)
Response.Write("<br>Price After 35% Discount = " & FinalPrice)

Response.Write("<p>--------------------------------------------------</p>")

FinalPrice# = CalculateNetPrice(Rate)
Response.Write("Original Price = " & OriginalPrice)
Response.Write("<br>Price After 35% Discount = " & FormatNumber(FinalPrice, 2))
%>

</body>
</html>

This would display:

Format Number

As a third alternative, you can call the Format() function. In reality, the second argument is used to format the number with many more options. To represent the integral part of a number, you use the # sign. To specify the number of digits to display on the right side of the decimal separator, type a period on the right side of # followed by the number of 0s representing each decimal place. Here is an example:

<%
Dim Number As Double

Number = 20502.48

Response.Write("Number: " & Format(Number, "#.00000"))
%>

The five 0s on the right side of the period indicate that you want to display 5 digits on the right side of the period. You can enter as many # signs as you want; it wouldn't change anything. To specify that you want to display the decimal separator, include its character between the # signs. Here is an example:

<%
    Dim Number As Double

    Number = 20502.48

    Response.Write("Number: " & Format(Number, "###,#######.00000"))
%>

Formatting a Percentage Value

Besides the Format() function, to support percent values, the Visual Basic language provides a function named FormatPercent. Its syntax is:

Function FormatPercent(
   ByVal Expression As Object,
   Optional ByVal NumDigitsAfterDecimal As Integer = -1,
   Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
   Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
   Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String

Only the first argument is required and it is the number that needs to be formatted. When calling this function, pay attention to the number you provide as argument. If the number represents a percentage value as a fraction of 0 to 1, make sure you provide it as such. An example would be 0.25. In this case, the Visual Basic interpreter would multiply the value by 100 to give the result.

Besides the FormatPercent() function, to format a number to its percentage equivalent, you can call the Format() function and pass the second argument as "Percent", "p", or "P".

 
 
   
 

Next Copyright © 2002-2016, FunctionX Next