Home

Built-In Functions: Format Percent

 

Introduction

To 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

As mentioned above, this function can be used in various scenarios. The simplest way to use this function is to pass it a number, a string, or a date/time). The function would then produce that number.

Besides the Format() function, the Visual Basic language provides some additional functions we will review below.

Formatting a Percentage Value

A percentage of a number represents its rate on a scale, usually of 100 (or more). The number is expressed using digits accompanied by the % sign. 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. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim DiscountRate As Double

        DiscountRate = 0.25

        MsgBox("Discount Rate: " & FormatPercent(DiscountRate))
        Return 0
    End Function

End Module

This would produce:

Format

On the other hand, if you pass the value in the hundreds, the interpreter would still multiply it by 100. Although it is not impossible to get a percentage value in the hundreds or thousands, you should make sure that's the type of value you mean to get.

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". Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim DiscountRate As Double

        DiscountRate = 0.25

        MsgBox("Discount Rate: " & Format(DiscountRate, "Percent"))
        Return 0
    End Function

End Module
 
 
     
 

Home Copyright © 2008-2016, FunctionX, Inc.