簡體   English   中英

如何使用此可視化基本代碼將列表框中的值四舍五入到小數點后兩位

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM