My calculation is throwing me crazy numbers... with letters
I was hoping someone could point me in the right direction as to what the heck I'm doing wrong here. I'm new to programming, and I'm doing the good 'ole mortgage calculator for a VB class.
My code should be giving me a monthly payment amount, but it's just giving me craziness. Can anyone spot what I'm doing wrong here? I'm very much a beginner so please bear with any seemingly silly code in here:
Public Class MortgageCalculator
'Module-level declarations
Const LOAN_AMOUNT_Integer As Integer = 200000
Const RATE_Double As Double = 0.0575
Const YEARS_Integer As Integer = 30
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click
'Dim declaration and calculation
Dim MonthlyPayment_Double As Double = (LOAN_AMOUNT_Integer * RATE_Double / (1 - (1 + RATE_Double ^ -YEARS_Integer)))
ResultLabel.Text = MonthlyPayment_Double
End Sub
Private Sub MortgageCalculator_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Label2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CreditLabel.Click
End Sub
Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
'Exit the project
Me.Close()
End Sub
Private Sub 开发者_如何学运维DescriptionLabel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DescriptionLabel.Click
End Sub
End Class
The E's are appearing because of the formatting on double - see Tim's excellent post for how to fix that. Why you're getting the wrong number in the first place is because your formula is wrong. The value you've been given is the yearly rate, but it compounds monthly. So you want your rate to be divided by months per year whenever it's used, and years to be multiplied by months per year. (Also, you needed to make 1 + rate be raised to the exponent, not just rate)
Dim MonthlyPayment_Double As Double = LOAN_AMOUNT_Integer * RATE_Double / 12 _
/ (1 - (1 + RATE_Double / 12) ^(-12 * YEARS_Integer))
You're trying to assign a double to a text (string). You also might be getting exponential numbers (represented by an E in the result). Try this:
ResultLabel.Text = MonthlyPayment_Double.ToString("F2")
The second one will format the string with 2 digits after the decimal place.
Edited to remove first suggestion
Your Hungarian Notation for variables (other than controls) not-with-standing, it looks like this line is the problem:
Dim MonthlyPayment_Double As Double = (LOAN_AMOUNT_Integer * RATE_Double / (1 - (1 + RATE_Double ^ -YEARS_Integer)))
You may have the order of operations incorrect. It might be:
Dim MonthlyPayment_Double As Double = (LOAN_AMOUNT_Integer * RATE_Double) / (1 - (1 + RATE_Double ^ -YEARS_Integer))
and you are also attempting to set the result into a text field:
ResultLabel.Text = Convert.ToString(MonthlyPayment_Double)
精彩评论