简体   繁体   English

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

[英]How to I make the values in the list box round to two decimal places with this visual basic code

I have written this code in visual basic to solve a basic interest calculation. 我已经用Visual Basic编写了这段代码来解决基本兴趣计算。 The year end balances are shown in the list box and the final total is show in the label. 年末余额显示在列表框中,最终总计显示在标签中。 My problem is that I can not figure out how to round the values in the list box to two decimals. 我的问题是我无法弄清楚如何将列表框中的值四舍五入到两位小数。 I have tried various things but with no luck so far so I appreciate any help. 我已经尝试过各种方法,但到目前为止还算不上运气,因此,我感谢任何帮助。

Public Class frmNestEgg Private Sub btnPrincipal_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click ' Declare and Initialize the variables 公共类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

End Class 末级

you could use 你可以用

Math.Round() 
... & Math.Round(YrEndAmt, 2).ToString()

but your code had a flaw: same variable Years for looping and end condition 但是您的代码有一个缺陷:循环和结束条件的变量Years相同

so change: 所以改变:

    For Years = 1 To Years

to: 至:

    Dim Years As Integer, year As Integer

    For year = 1 To Years

your entire code would then be: 您的整个代码将是:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM