[英]How to I make the values in the list box round to two decimal places with this visual basic code
我已经用Visual Basic编写了这段代码来解决基本兴趣计算。 年末余额显示在列表框中,最终总计显示在标签中。 我的问题是我无法弄清楚如何将列表框中的值四舍五入到两位小数。 我已经尝试过各种方法,但到目前为止还算不上运气,因此,我感谢任何帮助。
公共类frmNestEgg私有子对象btnPrincipal_Click(作为对象发送,作为EventArgs发送)处理btnCalculate.Click'声明并初始化变量
Dim Principal As Double = txtPrincipal.Text
Dim InterestRate As Double = txtInterestRate.Text / 100
Dim Years As Integer
Dim FinalTotal As Double
Dim YrEndAmt As Double
Years = Integer.Parse(txtYears.Text)
'Calculate the interest from the principal payment over the years input to create a total value.
For Years = 1 To Years
FinalTotal = Principal * Math.Pow((1 + InterestRate), Years)
YrEndAmt = (FinalTotal - Principal) + Principal
lstYrEndAmt.Items.Add("Year" & Years & " Balance " & YrEndAmt)
lblFinalTotal.Visible = True
lblFinalTotal.Text = FinalTotal.ToString("f1")
Next
End Sub
Private Sub frmNestEgg_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
末级
你可以用
Math.Round()
... & Math.Round(YrEndAmt, 2).ToString()
但是您的代码有一个缺陷:循环和结束条件的变量Years
相同
所以改变:
For Years = 1 To Years
至:
Dim Years As Integer, year As Integer
For year = 1 To Years
您的整个代码将是:
Private Sub btnPrincipal_Click(sender As Object, e As EventArgs) Handles btnPrincipal.Click
Dim Principal As Double = txtPrincipal.Text
Dim InterestRate As Double = txtInterestRate.Text / 100
Dim Years As Integer, year As Integer
Dim FinalTotal As Double
Dim YrEndAmt As Double
Years = Integer.Parse(txtYears.Text)
'Calculate the interest from the principal payment over the years input to create a total value.
For year = 1 To Years
FinalTotal = Principal * Math.Pow((1 + InterestRate), Years)
YrEndAmt = (FinalTotal - Principal) + Principal
lstYrEndAmt.Items.Add("Year" & year & " Balance " & Math.Round(YrEndAmt, 2).ToString())
lblFinalTotal.Visible = True
lblFinalTotal.Text = FinalTotal.ToString("f1")
Next
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.