Data Conversions
Data Conversions
Example:
Dim number As Integer, msg As String
number = 44545
msg = number
Print msg
Visual Basic converts the types wherever it can, and you have to convert the values into appropriate type in other cases.
Explicit conversion
In many cases you have to explicitly convert the data values to another data type.
Visual Basic has provided so many useful conversion functions.
Output: 6
Conversion functions
The functions are CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, and CVar.
Val and Str functions are also used.
Press F2 and type in the search box “Conversion”, then you’ll see all the functions with details under the Conversion module. All the
data type conversion functions are explained below.
NOTE: The argument of such function must be within the range of that particular data type, into which the value is converted.
CStr
The Cstr function converts an expression to a string. This is useful when you’re displaying some numeric values in a text box control.
Example:
Dim v1 As Double
Text1.Text = CStr(v1)
Str
The Str function converts a number to a string. It is similar to the Cstr function.
Example:
Dim str1 As String, m As Integer
str1 = Str(m)
While programming you’ll need the string representation of a number so many times.
CDbl
The CDbl function converts an expression into a Double. It also extracts the numeric value from a string.
Example: If you omit the CDbl function, the program will raise an overflow error.
Dim m As Integer, v As Double
m = 30887
v = CDbl(m) * 31880
Print v
Example:
Dim value As Double
value = CDbl(Text1.Text)
Print value + 1
Example:
Dim value As Double
value = CDbl("55")
Print value + 1
Val
Sometimes you can use the Val function instead of the CDbl function. Val function returns a Double value. It only returns the
numeric value contained in a string. Unlike the CDbl function, it cannot convert a numeric expression.
Example:
Dim l As Double
l = Val(Text1.Text)
CInt
The CInt function converts a number to integer.
Example:
Dim m As Integer
m = CInt(876.878) 'Returns 877 after roundin the no.
m = CInt(-2.7) 'Returns -3 after rounding the no.
CLng
The CLng function converts to Long type.
Example:
Dim ln As Long
ln = CLng(1147483647.87656) 'Rounds up the value
Debug.Print ln
CBool
The CBool function converts an expression to Boolean Data type, i.e either True or False.
The value of zero is converted to False and all other numeric values are converted to True. The strings “True” and “False” return
True and False Boolean values respectively.
Example:
Dim B as Boolean
B=cbool(0) 'Returns False
B=cbool(1) 'Returns true
B=cbool(345) 'Returns True
CByte, CSng, CVar,CCur,CDate and CDecimal functions convert to Byte, Sinle, Variant, Currency, Date and Decimal values
respectively. You can use these functions in the same way explained above.