How to convert answer to two decimal points

This is my code, and I need the output txtA.Text and txtB.Text 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 
+4
source share
5 answers

Try using the Format function:

 Private Sub btncalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncalc.Click txtA.Text = Format(Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text), "0.00") txtB.Text = Format(Val(txtA.Text) * 1000 / Val(txtG.Text), "0.00") End Sub 
+7
source

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"); 
+9
source

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 
+4
source

Call me lazy, but:

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

Ie: Label lblTellBMI will display your BMI: and then add the value from the Single type variable (sngBMI) as 2 decimal points, simply using the Math.Round method.

The Math.Round method rounds the 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

+2
source

Let's start this problem today, and I wrote a function for it. In my particular case, I needed to make sure that all values ​​are at least 0 (hence the name "LT0") and 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 probably looking for. End Function 
+1
source

Source: https://habr.com/ru/post/1481111/


All Articles