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.

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)

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

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.

didnt work, the message box prints "185 34225"

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.

Did you try 1,85 instead of 1.85?

facepalm that worked...

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.