CDec, CInt, CStr and CDate in Visual Basic
By Floyd Jay Winters 02/22/2010, 09/28/2012, 09/03/2014


CDec
: built-in function used to Convert an object to a Decimal, with Decimal attributes.

CInt: built-in function used to Convert an object to an Integer (a whole number)
CStr: built-in function used to Convert an object to a String (text or alpha-numeric data)
CDate: built-in function used to Convert an object to a Date, with Date attributes
Dim
: Command to Define, set data type, initialize values, and reserve space in memory for Variables

 

Dim Qty As Integer

Dim Price, Total As Decimal
Dim TaxRate As Decimal = .07

Qty = CInt(txtQuantity.Text)

Price = CDec(txtPrice.Text)

' or: lblPrice.Text = CDec(Val(txtPrice.Text))
' or: Price = Convert.ToDecimal(txtPrice.Text)

 

Total = Price * Qty
lblPrice.Text = FormatCurrency(Price, 2)

lblTotal.Text = FormatCurrency(Total, 2)

' The above is helpful when you cannot calculate on a text field that is formatted

' as currency due to the fact that the $ is not numeric, and a comma is not numeric.

' Although it is formatted as currency and cannot be used in a calculation, the original value is preserved and can be used later as a variable.

 

Other conversion Functions (there are many other conversion functions):

 Dim Name As String

 Name = CStr(txtName.Text)

 lblName.Text = CStr(txtName.Text)

 

 Dim TodaysDate As Date

 TodaysDate = CDate(txtDate.Text)

 

Some reasons to Convert:

Option Strict On “does not allow implicit conversions from String to Integer”

If the expression passed to the function is outside the range of the data type to which it is to be converted, an OverflowException occurs.

CDate recognizes date literals and time literals but not numeric values.