Type Conversion Functions

Each function coerces an expression to a specific data type.

Syntax

CBool([expression])

CByte([expression])

CDbl([expression])
CInt([expression])
CLng([expression])
CSng([expression])
CVar([expression])
CStr([expression])
CDate([expression])

CVDate([expression])

The optional expression argument is any string expression or numeric expression.

Return Types

Function Return Type
CBool Bool
CByte Byte
CDbl Double
CInt Integer
CLng Long
CSng Single
CVar Variant
CStr String
CDate Date
CVDate Date


Remarks

If the expression passed to the function is outside the range of the data type being converted to, it's transformed according to the following rules (on example of CInt):

CInt

-32768(min).....................0........................32767(max)

CInt(32768) returns -32768

CInt(32769) returns -32767

...

CInt(-32769) returns 32767

CInt(-32770) returns 32766

In general, you can document your code using the data-type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.

When the fractional part is exactly 0.5, CInt and CLng as well as CByte always round it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2. CInt and CLng differ from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. Also, Fix and Int always return a value of the same type as is passed in.

If the expression argument is omitted, CVar and CStr return an empty string, other functions return 0.

A CVDate function is identical to CDate and is provided for compatibility with other versions of BASIC.

Example

Dim  MyDouble, MyInteger, MyDate
MyDouble = CDbl("3.2")   ' Convert result to a Double -> 3.2
MyInteger = CInt(MyDouble)   ' Convert result to a Integer -> 3
MyDate = CDate(MyInteger) ' Convert result to a Date -> 2 Jan 1990

 

See Also

Fix Function, Int Function , Round Function