Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use CDbl and CStr functions using Visual Basic

I'm learning to use this program. I'm a few weeks into learning it, and I'm understanding most of it fine, but I just cannot get a grasp on when to use the CDbl, CInt, CStr, etc. functions. Here's an example of a few lines of code I can't get a grasp of:

If IsNumeric(txtFirst.Text) And IsNumeric(txtSecond.Text) Then
  txtSum.Text = CStr(CDbl(txtFirst.Text) + CDbl(txtSecond.Text))

This program is supposed to take two numbers that are input by the user and add them together. Simple. I was playing around with it, and I took out the CDbl and CStr functions, and the two numbers that were supposed to be added together were only added side by side (for example, if I input 2 and 15 as my numbers it would spit out 215).

So I'm curious when to use these functions.

How come on the second line, it says CStr(CDbl(? Why would I need to convert to double, THEN to string? Which is my understanding, unless I am reading this wrong.

Another question I have is, if I declare var1 as Dim var1 as Double. I constantly see the next line as var1 = CDbl(txtbox.text) and so on. I don't understand why we need to convert to Double here, since when I declared the variable as a double, it should already be in a double form already, shouldn't it?

like image 572
Tycholiz Avatar asked Sep 03 '26 00:09

Tycholiz


1 Answers

  1. The inner CDbl(txtFirst.Text) converts the first textbox's value to a number. The outer CStr(... + ...) converts the whole sum back to a string.

  2. Your variable is declared as a Double, but the Text property is a String.
    You need CDbl to convert the string to a number so that it can fit inside the variable.

like image 162
SLaks Avatar answered Sep 05 '26 16:09

SLaks