9

这是我的代码,我希望输出为txtA.TexttxtB.Text 为小数点后两位。

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

6 回答 6

14

有关格式选项,请参阅

Dim v1 as Double = Val(txtD.Text) / Val(txtC.Text) *
                   Val(txtF.Text) / Val(txtE.Text)
txtA.text = v1.ToString("N2");
于 2013-05-16T08:54:49.773 回答
8

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
于 2013-05-16T18:34:45.980 回答
8

尝试使用该Format功能:

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
于 2013-05-16T08:53:57.550 回答
3

叫我懒惰,但是:

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

即:标签lblTellBMI将显示Your BMI is:然后将来自Single类型变量 ( sngBMI ) 的值附加为 2 个小数点,只需使用Math.Round方法即可。

Math.Round方法将值四舍五入为最接近的整数或指定的小数位数。

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

于 2016-05-11T20:44:53.327 回答
1

今天遇到这个问题,我为它写了一个函数。在我的特殊情况下,我需要确保所有值至少为 0(因此称为“LT0”名称)并四舍五入到小数点后两位。

        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
于 2016-12-07T02:04:41.450 回答
0

如果您只想以特定格式打印小数点后 2 位的十进制数,无论本地人使用这样的东西

dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))
于 2019-03-22T09:46:32.957 回答