reconbobber - 9 months ago 40

Vb.net Question

I have written this code in visual basic to solve a basic interest calculation. 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

`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

Answer Source

you could use

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

but your code had a flaw: same variable `Years`

for looping and end condition

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
```