How to code Auto Loan calc with fixed months and interest? (VB) - vb.net

I need to make an auto loan calculator that is only able to calculate 2.3% interest for 84 months. I've never made a calculator that didn't allow a user to input these amounts, so how do I code that part of the calc?

Dim res As Decimal = 100 ' Current value
Dim interest As Decimal = 1.89 / 100 ' 1.89%
For i As Integer = 1 To 89 'Months
Dim amr As Decimal = res * interest
res += amr
Next
MsgBox(res)

Depends on what you want to calculate.. Monthly paiement, equity, what is left to pay ?
Here's the formula to calculate the monthly paiement of a loan
Dim monthlyPaiement As Decimal
Dim loanAmount As Decimal
Dim interestRate As Decimal
Dim loanLengthInMonth As Decimal
loanAmount = 25000
interestRate = 1.9 / 100
loanLengthInMonth = 84
interestRate /= 12 ' Divide by number of month in a year
monthlyPaiement = loanAmount * ((1 + interestRate) ^ loanLengthInMonth) * interestRate / (((1 + interestRate) ^ loanLengthInMonth) - 1)

Related

How do I get this mathematical rounding?

This is what I see in an official tool, and I need to calculate the same end value:
For clarification:
I am given the numbers 95, 3, 5, 19 and 17.15.
I am trying to replicate a math formula in VB.NET in order to achieve the same sum as a government financial tool that I must stay conform with.
The official tool's result and mine differ by 0.1 €, and I don't see what I need to do to achieve the same result.
The official tool states:
A product costs 95.00 € net.
Somebody buys 3 pieces of it.
He gets a discount of 5 % (=4.75 €)
19% VAT is added: 17.15 €
The net price is then 90.25 €
The price is now 270.75 €
The resulting end price is now 322.19 €.
The values that I am given are these:
net price for 1 piece: 95 €
amount: 3
discount per piece: 5%
VAT amount: 19%
VAT: 17.15
First, I calculate the discount like this:
Dim amount As Integer = 3
Dim discount As Double = 5
Dim VAT As Double = 17.15
All result As Decimal
Discount = (amount * discount) / 100 = 4.75
Discounted net price per piece = 95 - 4.75 = 90.25
Discounted net price per piece plus vat = 95 + 17.15 = 107.4
Total price result = discounted net price per piece * amount = 107.4 * 3 = 322.2 €
Is there anything that I'm doing wrong by choosing a wrong operator?
Is it even possible to get the same amount as they do with the information that I am given?
Thank you.
EDIT:
I just realised that you actually did use the correct discounted net price in the calculation below but you just wrote that you didn't, i.e. the result is correct even if the operands aren't.
ORIGINAL:
You do this:
Discounted net price per piece = 95 - 4.75 = 90.25
but then here:
Discounted net price per piece plus vat = 95 + 17.15 = 107.4
you don't use the result of that previous calculation.
Also, even if you did use the discounted price, how does it make sense to add a percentage to a price? Surely you need to calculate that percentage of that price, then add that result to that price. I would think that that line should be this:
Discounted net price per piece plus vat = 90.25 + (90.25 * 17.15 / 100) = 105.7(27875)
According to Decimal Data Type (Visual Basic):
The Decimal data type provides the greatest number of significant
digits for a number...It is particularly suitable for calculations,
such as financial, that require a large number of digits but cannot
tolerate rounding errors.
Try the following:
Create a Windows Forms App (.NET Framework) with the following TextBox names:
TextBoxPrice
TextBoxQuantity
TextBoxDiscountPercentage
TextBoxVATPercentage
TextBoxNetSalesPrice
TextBoxVATAmount
TextBoxGrossSalesPrice
and a Button (name: btnCalculate).
Try the following:
'for testing
Private cultureInfo As System.Globalization.CultureInfo = System.Globalization.CultureInfo.GetCultureInfo("de-DE")
'ToDo: use this one to use the current culture info of the computer
'Private cultureInfo As System.Globalization.CultureInfo = System.Globalization.CultureInfo.CurrentCulture
'get currency symbol
Private currencySymbol As String = cultureInfo.NumberFormat.CurrencySymbol
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim InitialPrice As Decimal = 95
Dim Quantity As Decimal = 3
Dim DiscountPercentage As Decimal = 5
Dim VATPercentage As Decimal = 19
'set value
TextBoxInitialPrice.Text = InitialPrice.ToString("N2", cultureInfo)
TextBoxQuantity.Text = Quantity.ToString("N0", cultureInfo)
TextBoxDiscountPercentage.Text = DiscountPercentage.ToString("N0", cultureInfo)
TextBoxVATPercentage.Text = VATPercentage.ToString("N0", cultureInfo)
End Sub
Private Sub Calculate()
Dim DiscountAmount As Decimal = 0
Dim DiscountPercentage As Decimal = 0
Dim NetPrice As Decimal = 0
Dim InitialPrice As Decimal = 0
Dim Quantity As Decimal = 0
Dim VATAmount As Decimal = 0
Dim VATPercentage As Decimal = 0
Dim GrossSalesPrice As Decimal = 0
'ToDo: Ensure that the user entered valid input. If not, notify the user of invalid input
'convert String to Decimal
Decimal.TryParse(TextBoxInitialPrice.Text, System.Globalization.NumberStyles.Currency, cultureInfo, InitialPrice)
Decimal.TryParse(TextBoxDiscountPercentage.Text, System.Globalization.NumberStyles.Number, cultureInfo, DiscountPercentage)
Decimal.TryParse(TextBoxVATPercentage.Text, System.Globalization.NumberStyles.Number, cultureInfo, VATPercentage)
Decimal.TryParse(TextBoxQuantity.Text, System.Globalization.NumberStyles.Number, cultureInfo, Quantity)
Debug.WriteLine($"A product costs {InitialPrice.ToString("N2", cultureInfo)} {currencySymbol} net.")
Debug.WriteLine($"Somebody buys {Quantity.ToString("N0", cultureInfo)} pieces of it.")
'calculate discount amount
DiscountAmount = Decimal.Multiply(InitialPrice, Decimal.Divide(DiscountPercentage, 100))
Debug.WriteLine($"He gets a discount of {DiscountPercentage.ToString("N0", cultureInfo)}% (={DiscountAmount.ToString("N2", cultureInfo)} {currencySymbol})")
'calculate net price
NetPrice = Decimal.Subtract(InitialPrice, DiscountAmount)
Debug.WriteLine($"The net price is then {NetPrice.ToString("N2", cultureInfo)} {currencySymbol}")
'calculate gross price
Dim NetSalesPrice As Decimal = Decimal.Multiply(NetPrice, Quantity)
Debug.WriteLine($"The price is now {NetSalesPrice.ToString("N2", cultureInfo)} {currencySymbol}")
'set value
TextBoxNetSalesPrice.Text = NetSalesPrice.ToString("N2", cultureInfo)
Debug.WriteLine($"{VATPercentage.ToString("N0", cultureInfo)}% VAT is added to this amount.")
'calculate VAT amount
VATAmount = Decimal.Multiply(NetSalesPrice, Decimal.Divide(VATPercentage, 100))
'set value
TextBoxVATAmount.Text = VATAmount.ToString("N2", cultureInfo)
'calculate grand total (gross sales price)
'GrossSalesPrice = Decimal.Multiply(NetSalesPrice, Decimal.Add(1, Decimal.Divide(VATPercentage, 100)))
GrossSalesPrice = Decimal.Add(NetSalesPrice, VATAmount)
Debug.WriteLine($"The resulting end price is now {GrossSalesPrice.ToString("N2", cultureInfo)} {currencySymbol}")
'set value
TextBoxGrossSalesPrice.Text = GrossSalesPrice.ToString("N2", cultureInfo)
End Sub
Usage:
Calculate()
Update:
From the code above one can extract the following formulas which were created using the information listed beneath The official tool states:
Formulas
DiscountAmount = InitialPrice * (DiscountPercentage / 100.0)
NetPrice = InitialPrice - DiscountAmount
NetPrice = InitialPrice - (DiscountAmount)
NetPrice = InitialPrice - (InitialPrice * (DiscountPercentage / 100.0))
NetSalesPrice = NetPrice * Quantity
VATAmount = NetSalesPrice * (VATPercentage / 100.0)
GrossSalesPrice = NetSalesPrice + VATAmount
Given the following:
NetPrice: 95
Quantity (amount): 3
DiscountPercentage: 5%
VATPercentage: 19%
VATAmount: 17.15
Formula #1: DiscountAmount = InitialPrice * (DiscountPercentage / 100.0)
Formula #2: NetPrice = InitialPrice - (DiscountAmount)
If one substitutes the DiscountAmount formula, in Formula #2, one has:
NetPrice = InitialPrice - (InitialPrice * (DiscountPercentage / 100.0))
Let's insert the information into the formulas:
95 = InitialPrice - (InitialPrice * (5 / 100.0))
95 = InitialPrice - (InitialPrice * 0.05)
Let's change InitialPrice to something that may be more familiar: x
95 = x - (x * 0.05)
95 = 1x - 0.05x
95 = 1.00x - 0.05x
95 = 0.95x
ToDo: Solve for x (InitialPrice).
Formula: NetSalesPrice = NetPrice * Quantity
Insert the information into the formula:
NetSalesPrice = 95 * 3
NetSalesPrice = 285
The information regarding VATAmount and VATPercentage, in the OP, seems to keep changing. Nevertheless, one uses simple algebra to solve for the unknown variable.
Formula: VATAmount = NetSalesPrice * (VATPercentage / 100.0)
Insert the information into the formula:
VATAmount = 285 * (19 / 100.0)
or given VATAmount = 17.15 instead of a VATPercentage:
17.15 = 285 * (VATPercentage / 100.0)
Once again, let's change VATPercentage to something that may be more familiar: x
17.15 = 285 * (x / 100.0)
17.15 = 285x / 100.0
17.15 * 100 = 285x
1715 = 285x
ToDo: Solve for x (VATPercentage).
Resources:
Decimal.Multiply
Decimal.Divide
Decimal.Add
CultureInfo
NumberFormatInfo.CurrencySymbol
Standard numeric format strings

Why does math.round not round to 2 digits?

Following VB.Net code does not return the expected result:
Dim sum As Single = 535353
Dim vat As Single = Math.Round(sum * 0.19, 2)
Dim total As Single = Math.Round(sum + vat, 2)
Debug.WriteLine(String.Format("sum: {0:c2}, vat: {1:c2}, total: {2:c2}", sum, vat, total))
vat is correctly set to 101717.07, but the result of "total" is 636070.063.
Why does the last Math.round function returns 3 digits, and the wrong result?
Try it using Double
Dim sum As Double = 535353
Dim vat As Double = Math.Round(sum * 0.19, 2)
Dim total As Double = Math.Round(sum + vat, 2)
' sum 535353.0 Double
' total 637070.07 Double
' vat 101717.07 Double

if statement to mathematical addition gives answer zero in vb.net

' total service till retirement
retirement = Me.DateTimePicker2.Value
appointment = Me.DateTimePicker1.Value
Dim workingTime As TimeSpan = retirement - appointment
Dim yearVal As Double = workingTime.TotalDays / 365
Dim years = CInt(Math.Floor(yearVal))
Dim monthVal = (workingTime.TotalDays - years * 365) / 30
Dim months As Int32 = CInt(Math.Floor(monthVal))
Dim dayVal = workingTime.TotalDays - (years * 365 + months * 30)
Dim days As Int32 = CInt(Math.Floor(dayVal))
Dim result = $" {years} years {months} months & {days} Days"
tservice.Clear()
tservice.Text = result
' Pay reckonable for pension.
reckonable = Val(lastpay.Text) + Val(increment.Text)
'17. Service on the date of retirement. rounded off
If months > 5 Then
totalyear = (Val(years) + 1)
End If
'1. PENSION:-17760x26x7/300=Rs. 10774.40
tpension.Clear()
pension = (Val(reckonable) * Val(totalyear) * 7 / 300)
tpension.Text = pension
i need that answer should not be zero but due to totalyear a integer variable inside if statement gives zero i want it to add a value 1 if num of months is greater than 5 kindly help me.

VB program to calculate monthly deposits plus interest

I am having issues trying to make a calculator that accurately calculates deposits plus the amount of interest that is added monthly. I dont know how to incorporate a loop that can add monthly deposits to total deposits, then adds the total deposits plus total interest times the interest rate / 100 / 12 to the total deposits. Here is what I have so far. Sorry am super new to VB !
Dim intMonthlyDeposit As Interger
Dim intMonthsTotal As Integer
Dim intAnnualRate As Interget
Dim decTotalDeposits As Decimal
Dim decTotalInterest As Decimal
Dim decTotalTotal As Decimal
Try
intMonthlyDeposit = CInt(txtMonthlyDeposits.Text)
intMonthsTotal = CInt(txtMonths.Text)
decAnnualRate = CDec(txtAnnualRate.Text)
decTotalDeposits = 0
decTotalInterest = 0
decTotalTotal = 0
decTotalDeposits = decMonthlyDeposit * intMonthsTotal
decTotalInterest = decTotalDeposits * (decAnnualRate / 100)
decTotalTotal = decTotalDeposits + decTotalInterest
lblTotDeposit.Text = decTotalDeposits.ToString("C")
lblTot.Text = decTotalTotal.ToString("C")
lblTotInterest.Text = decTotalInterest.ToString("C")
Catch ex As Exception
MsgBox("Enter a Valid Number")
End Try
End Sub
This is how I implemented the loop for calculating total interest and total deposits correctly.
For index As Integer = 1 To intMonthsTotal Step 1
decTotalDeposits += decMonthlyDeposit
decTotalInterest += (decTotalDeposits + decTotalInterest) * ((decAnnualRate / 100) / 12)

Receive "infinity" as result in mortgage payment calculation in Visual Basic

I'm a first year programming student and am trying to make a mortgage payment calculator. Users enter their loan amount and interest rate, select 15 or 30 years for the term length, and their monthly payment should be calculated. I think the math is correct, but I think I'm running into problems with converting data types. The only result I'm able to calculate is "Infinity". I've also tried declaring all variables as Doubles, but no difference.
Below is the piece of code I'm having trouble with, and Option Strict On is included in the full code. Any tips would be greatly appreciated!
Dim decLoanAmount As Decimal
Dim decInterestRate As Decimal
Dim decFifteen As Decimal = 180D
Dim decThirty As Decimal = 360D
Dim decNumberOfMonths As Decimal
Dim dblPayment As Double
Dim decPayment As Decimal
' Did user enter a numeric value?
If IsNumeric(txtLoanAmount.Text) And IsNumeric(txtInterestRate.Text) Then
decLoanAmount = Convert.ToDecimal(txtLoanAmount.Text)
decInterestRate = Convert.ToDecimal(txtInterestRate.Text)
' Is Loan Amount greater than zero?
If decLoanAmount > 0 And decInterestRate > 0 Then
If radFifteen.Checked = True Then
decNumberOfMonths = decFifteen
ElseIf radThirty.Checked = True Then
decNumberOfMonths = decThirty
End If
' Calculate the monthly payments as a double
dblPayment = (decLoanAmount * (decInterestRate / 12 / 100) * (1 + (decInterestRate / 12 / 100) _
^ decNumberOfMonths)) / ((1 + (decInterestRate / 12 / 100) ^ decNumberOfMonths) - 1)
' Convert double to decimal
decPayment = Convert.ToDecimal(decPayment)
' Display monthly payment
lblPayment.Text = decPayment.ToString("C2")
Else
If decLoanAmount < 0 Then
MsgBox("Please enter a valid loan amount.", , "Input error")
End If
If decInterestRate < 0 Then
MsgBox("Please enter a valid interest rate.", , "Input error")
End If
End If
Else
' Display error message if user entered a negative value.
MsgBox("Please enter a numeric value.", , "Input Error")
End If
End Sub
Based on the Wikipedia formula, you aren't doing it correctly. It should look something like this:
dblPayment = (decLoanAmount * (decInterestRate / (12 * 100))) / (1 - (1 + (decInterestRate / (12 * 100))) ^ (-decNumberOfMonths))
Also, this line is weird
decPayment = Convert.ToDecimal(decPayment)
Should be
decPayment = Convert.ToDecimal(dblPayment)