首页 文章

如何使用此可视基本代码将列表框中的值舍入到小数点后两位

提问于
浏览
0

我已经用Visual Basic编写了这段代码来解决基本的兴趣计算 . 年末余额显示在列表框中,最终总计显示在标签中 . 我的问题是我无法弄清楚如何将列表框中的值舍入为两位小数 . 我尝试了各种各样的东西,但到目前为止没有运气,所以我感谢任何帮助 .

公共类frmNestEgg Private Sub btnPrincipal_Click(sender as Object,e As 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

结束班

1 回答

  • 1

    你可以用

    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
    

相关问题