When to use CDbl and CStr functions using Visual Basic - vb.net

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?

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.
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.

To understand this code:
txtSum.Text = CStr(CDbl(txtFirst.Text) + CDbl(txtSecond.Text))
Let's separate it into pieces. First of all, value in a textbox control is of String type. In order to perform ADDITION, the string type needs to be converted into double type, so you do CDbl(txtFirst.Text) and CDbl(txtSecond.Text)
The ADDITION operation is done by CDbl(txtFirst.Text) + CDbl(txtSecond.Text). In order to assign the result of that ADDITION to a textbox control, you need to convert it to String type. So you do CStr() on CDbl(txtFirst.Text) + CDbl(txtSecond.Text). So the full operation in one line code is txtSum.Text = CStr(CDbl(txtFirst.Text) + CDbl(txtSecond.Text))

Related

VB.NET - Can't get Integer to work

I'm working with Windows Forms Application in Visual Studio 2015, using .NET Framework 4.5.2. So I'm making a simple program which includes a label to display a value. The label (called lblMoney) displays the currency (in this case, $) and then the value (e.g 350). Together it looks like $350.
Now, I made another form with a textbox called txtCash and a button called bApply. You enter any integer (e.g 350) into txtCash. When you press bApply, the number in txtCash will add to the number in lblMoney. So, if you had 5 in lblMoney, and you entered 350 in txtCash, lblMoney would display 355.
Here's my code to add to the number:
My.Forms.VeilSideCash.lblMoney.Text = cstrx + txtCash.Text.ToString
The form VeilSideCash is the form that holds lblMoney.
Here's the code for cstrx:
Dim cstrx = "$" & Val(My.Settings.Money.ToString)
The problem here is that, instead of overwriting to lblMoney, the new number is just added after the original number. So if lblMoney has 5 and you enter 350 into txtCash, lblMoney looks like $5350.
How would I go about overwriting with the new number (adding to) instead of replacing?
Any help would be appreciated. Feel free to edit incase I messed something up while explaining.
The problem with your code is the Option Strict setting for your project. You have it set to Off and this allows your code to freely treat strings as they were numbers and try to use them in mathematical operations.
But, when you use the + operator between two strings, it doesn't matter if, for a human being, the two strings represent a number, the compiler see them as strings (cstrx, txtCash.Text) and thinks that you want to use the concatenation operator defined for strings (the +). Yielding wrong (for you) results .
I really suggest you to not use the automatic conversions made by the compiler on your code, instead, when you need to do math operations, always convert your strings to numbers and do the math with variables of numeric type (You could also change the Option Strict to On, but you should be prepared to solve a lot of problems in your current code)
Instead, with a proper numeric approach, you get the text inside txtCash and try to check if your user has correctly typed a decimal value.
Dim cash As Decimal
if Not decimal.TryParse(txtCash.Text, cash) Then
MessageBox.Show("Invalid cash value")
Return
End if
Now get the text of lblMoney and convert it back to a decimal number alerting the compiler that there is a currency symbol in the text to convert
Dim current As Decimal
current = decimal.Parse(lblMoney.Text, NumberStyles.Currency, CultureInfo.CurrentCulture)
Now you have two numbers and the + operator does what you expect. It adds the two numbers together. Finally you could write back the result with a proper currency formatting
Dim result as Decimal
result = current + cash
lblMoney.Text = result.ToString("C")
You need to remove the "$" and convert to a number. I used a decimal so you can include cents if you want:
Dim sum As Decimal
sum = Val(cstrx.Replace("$","")) + Val(txtCash.Text)
My.Forms.VeilSideCash.lblMoney.Text = sum.ToString()
Dim cstrx = sum.ToString("C")
Note that I used the "C" to format the sum as currency. That automatically puts the $ on for you, or uses other currency symbols for other countries.
I'm not a big VB.net user, so my syntax may be slightly off.
When you use the + operator with string unexpected results can occur. In this case the string with a $ cannot be implicitly converted so you should explicit convert it
Once you convert your strings to a number type you can then use the + operator and they can be implicitly converted back to a string.
My.Forms.VeilSideCash.lblMoney.Text = decimal.Parse(cstrx, NumberStyles.Currency)
+ decimal.Parse(txtCash.Text ,NumberStyles.Currency)

Values not calculating in Userform

Can someone please help me.
I have a userform which has a number of numeric fields. The issue is that my Total box will not calculate them as it is recognising a number as text. So for example if I was to say HE.Value (10) + ME.Value (10) for example should = 20 however is the Total is coming to 1010. and if I * it instead I am receiving an error to debug as it recognises the value as text format.
I have never had this issue in a userform before. Is someone able to assist please?
Thanks,
You have:
totalBox.Text = box1.Text + box2.Text
When the two operands are String, the + operator works as a string concatenation operator, meaning it works exactly like the & operator. That's how you get 1010 instead of 20: VBA thinks you're asking it to concatenate strings.
VBA cannot do arithmetics on strings, so if your strings represent numeric values, you need to convert them first.
If you're only working with integers then you can do this with the CLng type conversion function:
totalBox.Text = CStr(CLng(box1.Text) + CLng(box2.Text))
Notice this makes the back-to-string conversion explicit (CStr); leave it out and VBA will perform that type conversion implicitly.

Convert to double - questionable accuracy

I'm using Convert.ToDouble(value) to convert an OleDbDataReader type to Double but sometimes it adds extra decimals (I'm working with Access).
Example:
Lets say data(0) is holding the value 69,8 (with comma)
Then this is my code:
Dim data As OleDbDataReader = DBBroker.getInstance.read("SELECT ......")
Dim m as Double = Convert.ToDouble(data(0))
My problem is that this is making m something like 69.80002302 (or something similar) instead of just 69.8 like it really containss.
Why? How can I solve it?
Well, are you really sure that the field really contains exactly 69.8 or, simply, Access is rounding out the value?
If you really want to be extra sure about what's inside the reader, you can debug into the code and use .IsDbNull(0) to check if the value it's null. If it's not, look at the actual type of data(0) in the Locals tab in Visual Studio. If it's already a double, then no conversion is happening, and I suspect the field is already storing a rounded value.

input string is not in the correct format - double type

I have two text boxes that have double value and i need to calculate the yield. I have changed the code to use Double.Parse now and i am still getting the same result. Attached image shows the error and my run time value. x and y place holder variables have my values. What am i missing here?
Dim FinalProdWt as Double = 0.0
Dim TargetWt as Double = 0.0
Double.Parse(txtFinalProdWt.Text, FinalProdWt)
I am getting "input string was not in correct format" exception. I have been using vb.net after a long time (13 years) and i can't replicate the issue in sample C# code.
You're calling Double.Parse like it was Double.TryParse. That code should be:
FinalProductWt = Double.Parse(txtFinalProductWt.Text)
You must have Option Strict Off or you'd have been warned that your second argument was not the correct type. Turn Option Strict On and leave it On.
I was actually thinking when I first looked at the code that you really should be calling TryParse rather than Parse, so maybe your mistake was actually calling the wrong method rather than passing the wrong arguments.

VB.Net Currency Converter - Is there an easier way?

Just picked programming up as a hobby, and am very bad. I am trying to build a basic currency converter from the book I have.
My question: Is there is a better way than taking the user input (lets say 5 dollars), convert the text string to a double, multiply by the rate, and then convert it back to a string in order to display it in the other textbox? I mainly ask because the textbook hasn't said how to convert double to string yet, and I found it online but I feel like I'm missing something.
Thanks
Whenever you're working with money, use the Decimal type. It works just like Double in every way, except that Double is not 100% accurate for certain arithmetic operations. Decimal is a bit slower, but it's accurate, and when you're working with money, the accuracy is almost always more important.
the textbook hasn't said how to convert double to string yet
That's easy:
'The "D" at the end is a special code that means it's a Decimal literal value
Dim d As Decimal = 12345.67D
Dim s As String = d.ToString()
Going the other direction isn't much harder:
Dim d2 As Decimal = Decimal.Parse(s)