0

Hi, In an application im making, I need to square a decimal value in a text field to then use in other calculations later, but when the compiler squares the value it ignores the decimal points, treating 1.85^2 as 185^2 and returning 34225 rather than 3.4225. What am I doing wrong? Here is the code:

    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
        Dim heightSquared, height As Double
        height = txtHeight.Text
        heightSquared = (height * height)
        lblBMI.Text = heightSquared
    End Sub

This is the test code im using, and have tried using height^2 and got the same result.

4
Contributors
10
Replies
32
Views
4 Years
Discussion Span
Last Post by KenSquare
0

Hmmm... I ran your code and had no problem! I get 3.4225.
Are you using a font that might not show the decimal or it is too small to see?
Try putting a msgbox to test the value after the calculation:
MsgBox(height & " " & heightSquared)

0

returns the exact same value, it jsut ignores the decimal point. Does VB 2012 and VB 2010 treat decimals differently or something? I'm using the 2012 compiler...

0

Try using :

Dim heightSquared, height As Double
If Double.TryParse(txtHeight.Text, height) Then
    heightSquared = height * height
    lblBMI.Text = heighSquared.ToString()
Else
    MessageBox.Show("Height must be a number")
End If

This will validate the input from the textbox and convert the text to double properly.
These kinds of problems abound when you program without all your Options on.

0

Can you post a screen shot of your form with the value in the textbox and the result?
tinsaafl is suggesting that you turn on "Option Strict", I believe.

0

Glad to be of help.
In America a point is used in Europ we use a comma as decimal separator.
Always use TryParse(as proposed by tinstaafl here) so you can detect wrong formats in your numbers.

0

I never would have thought of that... Thanks ddanbe. That goes in the memory banks.
Sam, you put Option Strict On and Option Explicit On before Public Class. I did not have Option Strict On either - it is best practice. There is also some place to set it so that it is already on in the environment so that it does not have to be stated each time, I cannot recall where. When I took a class in VB, if you did not show these on, you got points off.

Edited by KenSquare: corrected mistake.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.