More on Visual Basic Conversion Functions

CStr converts a double or integer to a string.
CDbl will convert a string to a decimal number.
CInt will convert a string to a integer.

Reading numbers

When you read from a textbox, you are reading a string value, even if it contains a number. Basically a number in a textbox is treated like a string until it is converted to a number using CDbl or CInt. CDbl gives you a decimal value, and CInt an integer. Which one you use depends on whether you expect an decimal or integer value in the text box. There is no harm in using CInt even if there is an decimal value in the textbox. You will however lose the decimal part since CInt returns only the integer portion.

Example: Suppose we have a textbox that contains a number. If we expect it to be a decimal number we would use CDbl to convert it into a double inside visual basic: X = CDbl(text1.text).
If we expect an integer value, then we use: X = CInt(text1.text). We can now use X in calculations.

Printing numbers

We usually print our answers in the caption property of labels. Since label captions expect strings to be printed in them, we should convert all numbers to strings before trying to put them into a label caption. This is done using the CStr function. This function can take either an integer or decimal value and convert it to a string.

Example: To print the value of X in a label we would use: Label1.Caption := CStr(X);

Rounding numbers

You only need to round decimal numbers that have more decimal places than you want to print. For example if I have an equation such as: miles = kilometers * 0.62, my answer will have a lot of decimal places. Since I only want to see the first two decimal places when I print it, I should round the answer to two decimal places before printing it to the label. This could be accomplished like this:
miles = round(kilometers * 0.62, 2)
mileslbl.caption = CStr(miles)

The IsNumeric function

This topic is not required for this assignment. However, I will present it in case you want to try it.

Using CDbl or CInt on a textbox that does not contain a number will cause Visual Basic to stop running and give you an error. To avoid this, you can check the textbox value to make sure it is a number before you try to convert it. This is done using the IsNumeric function and an If statement. Then we can perform our calculations if it is a valid number otherwise we could print an error message:

Example:
if isnumeric(kmtxt.text) then
  km = CDbl(kmtxt.text)
  miles = round(km * 0.62)
  mileslbl.caption = CStr(miles)
else
  error1.caption = "Please enter a valid number"
endif


Main Visual Basic Page | My Home Page

Page created and maintained by Ron Patterson


since April 6, 2002