[vb.net] How to convert answer into two decimal point

This is my code and I want the output which is txtA.Text and txtB.Text to be in two decimal places.

Public Class Form1
    Private Sub btncalc_Click(ByVal sender As System.Object,
                              ByVal e As System.EventArgs) Handles btncalc.Click
      txtA.Text = Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)
      txtB.Text = Val(txtA.Text) * 1000 / Val(txtG.Text)
    End Sub
End Class

This question is related to vb.net

The answer is


Call me lazy but:

 lblTellBMI.Text = "Your BMI is: " & Math.Round(sngBMI, 2)

I.e.: Label lblTellBMI will display Your BMI is: and then append the value from a Single type variable (sngBMI) as 2 decimal points, simply by using the Math.Round method.

The Math.Round method rounds a value to the nearest integer or to the specified number of fractional digits.

Source: https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx


For formatting options, see this

Dim v1 as Double = Val(txtD.Text) / Val(txtC.Text) *
                   Val(txtF.Text) / Val(txtE.Text)
txtA.text = v1.ToString("N2");

Ran into this problem today and I wrote a function for it. In my particular case, I needed to make sure all values were at least 0 (hence the "LT0" name) and were rounded to two decimal places.

        Private Function LT0(ByVal Input As Decimal, Optional ByVal Precision As Int16 = 2) As Decimal

            ' returns 0 for all values less than 0, the decimal rounded to (Precision) decimal places otherwise.
            If Input < 0 Then Input = 0
            if Precision < 0 then Precision = 0 ' just in case someone does something stupid.
            Return Decimal.Round(Input, Precision) ' this is the line everyone's probably looking for.

        End Function

If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this

dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))

If you have a Decimal or similar numeric type, you can use:

Math.Round(myNumber, 2)

EDIT: So, in your case, it would be:

Public Class Form1
  Private Sub btncalc_Click(ByVal sender As System.Object,
                            ByVal e As System.EventArgs) Handles btncalc.Click
    txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
    txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
  End Sub
End Class