I hope someone can help with this:
I am currently working on a motor dealership website. On this website is a car loan calculator that calculates your monthly repayments. I have successfully created a basic calculator that calculates the correct amount.
The client isn't happy with that. They want a more advanced calculator that calculates the monthly repayments with balloon considerations and a deposit and initiation and admin fees.
I altered the code to reflect that, but now the thing won't work anymore. I can't find any error in my code.
Here's the Javascript that's supposed to do the calculation:
function calculate() {
// Get the user's input from the form. Assume it is all valid.
// Convert interest from a percentage to a decimal, and convert from
// an annual rate to a monthly rate. Convert payment period in years
// to the number of monthly payments.
var principal = document.loandata.principal.value;
var lessDeposit = document.loandata.deposit.value;
var adminFee = document.loandata.admin.value;
var initiationFee = document.loandata.initiation.value;
var interest = document.loandata.interest.value / 100 / 12;
var payments = document.loandata.years.value * 12;
var balloonPercent = document.loandata.balloon.value / 100;
// Now compute the monthly payment figure, using esoteric math.
var balloonFinal = (principal * balloonPercent);
var totalPrincipal = (principal + initiationFee + balloonfinal - lessDeposit);
var x = Math.pow(1 + interest, payments);
var monthly = (totalPrincipal*x*interest)/(x-1);
// Check that the result is a finite number. If so, display the results
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {
document.loandata.payment.value = round(monthly + adminFee);
document.loandata.total.value = round(monthly * payments);
document.loandata.totalinterest.value =
round((monthly * payments) - principal);
}
// Otherwise, the user's input was probably invalid, so don't
// display anything.
else {
document.loandata.payment.value = "";
document.loandata.total.value = "";
document.loandata.totalinterest.value = "";
}
}
// This simple method rounds a number to two decimal places.
function round(x) {
return Math.round(x*100)/100;
}
Also, if possible, there needs to be some validation. Like purchase price, interest rate and payment period are required fields. But the rest are not. So if someone fills in the required fields but not the rest, the calculator still needs to work, but if someone does NOT complete one of the required fields, they need to be prompted to do so.
For those who don't know what a balloon payment is, here's an example;
Purchase Price is R117 000
You decide on a balloon payment of 30%. On the initial purchase price, the 30% amounts to R35 100. This amount is then subtracted from your initial purchase price so that means your purchase is now R81 900. After that comes the deposit, which is subtracted, and the extras and the admin and initiation fees. So the monthly repayments are calculated using this new purchase price of R81 900 + extras - deposit (if any). For interest sake, after your contract ends, you have to pay the balloon amount in full or re-finance the vehicle.
PS: I'm a complete newbie when it comes to JavaScript. So any help would be greatly appreciated.
If the result is nothing, one of these three conditions is likely triggering the else statement:
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {
You have a typo in the JS, you need to change balloonfinal to be balloonFinal with a capital F in the var totalPrincipal = line of code.
The principal, lessDeposit, adminFee, initiationFee may also need to be typecast as an integer/float.
Related
Alert: shameless homework help.
I am trying to create an amortization schedule for paying off a credit card. I'm stuck because I think I need to create a loop that does all the calculations until the credit card balance is zero. I know basic loops, I know basic objects; and, referencing a different function (aka not local function) for the payment id. Combining the principles is baffling me atm.
Full problem details commented out in code.
Ive tried messing around with different loop ideas; after I'm asking for loop help, i think. I cant get the loop to work, it usually ends up being infinite and crashing the browser. But in relation to above criteria confuses me a bit.
function displayWelcome() {
printLine();
console.log('Welcome to the credit card payoff tool.');
printLine();
console.log('This program will determine the time it \nwill take to pay off a credit card!');
printLine();
}
displayWelcome();
function calculateMinimumPayment(balance, interestRate) {
var calcMinPay = balance * interestRate;
return calcMinPay
}
function generatePaymentId() { // lines 14 - 22 are a closure function.
var count = 0;
function paymentId() {
count ++;
return count;
}
return paymentId;
};
var id = generatePaymentId();
function processPaymentSchedule(balance, interest, minimumPayment) {
var year = 1;
var counter = 0;
while (balance > counter) {
var interestDecimal = interest / 100;
var interestMonthly = interestDecimal / 12;
var interestPaid = balance * interestMonthly;
var payment = {
year: year,
balance: balance,
paymentId: id(),
interest_paid: interestPaid
}
displayPayment(payment);
balance = balance - interestPaid;
return balance;
}
}
function displayPayment(payment) {
console.log(payment.year);
}
printLine();
function printLine() {
console.log('---------------------------------------');
}
printLine();
processPaymentSchedule(1500,18, calculateMinimumPayment());
/*
It should take the balance monthly interest rate and minimum payment as arguments. Each time you calculate a new payment line, create an object literal with properties for the year balance and payment id and interest paid. Pass this object literal to the displayPayment function.
*/
Given these numbers (balance=1500, interest=18%, minimumPayment(a separate function showing 2% of the balance as minimum payment.))
Year / Balance / PaymentID / InterestPaid
1 1492.50 1 22.50
1484.89 2 67.16
(continue to till balance is zero)
So I`m trying to format my number to include percentage sign using script editor
That "valuetoCheck" is the target i`m trying to change
I am sending these emails to my colleagues when error rate is greater than 10 %
That 'J1' is basically extracted from the sheet by using formula (=max(C:C)) and they are already in percent format in actual google sheet itself
How should I format that J1 so that it can be shown with proper percent sign in the email?
The current code generates the below message in the email..
Reported Maximum default rate is: 0.020380774742397016
and the number is supposed to be 2% if it was done properly
function checkValue()
{
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Final_Report');
var url = ss.getUrl();
var valueToCheck = sheet.getRange('J1').getValue();
var emailSendTo = 'random#hotmail.com'
var subject = "Errpr - Detected!";
var message = "Please check Error rates \n\n Reported Maximum Error rate is: " + valueToCheck
if(valueToCheck > 0.1)
{
MailApp.sendEmail(emailSendTo, subject, message);
}
}
Regardless of how it is formatted, the "value" will still be '0.020380774742397016'.
An option is to round the value, then multiply by 100 to allow you to display it as a percentage. Something like:
var valueToReport = (+valueToCheck.toFixed(4))*100;
var message = "Please check Error rates \n\n Reported Maximum Error rate is: " +valueToReport+"%";
This will display the value as "2.04%"
I came across this program from a You Don't Know JS books book on github:
const SPENDING_THRESHOLD = 200;
const TAX_RATE = 0.08;
const PHONE_PRICE = 99.99;
const ACCESSORY_PRICE = 9.99;
var bank_balance = 303.91;
var amount = 0;
function calculateTax(amount) {
return amount * TAX_RATE;
}
function formatAmount(amount) {
return "$" + amount.toFixed( 2 );
}
// keep buying phones while you still have money
while (amount < bank_balance) {
// buy a new phone!
amount = amount + PHONE_PRICE;
// can we afford the accessory?
if (amount < SPENDING_THRESHOLD) {
amount = amount + ACCESSORY_PRICE;
}
}
// don't forget to pay the government, too
amount = amount + calculateTax( amount );
console.log(
"Your purchase: " + formatAmount( amount )
);
// Your purchase: $334.76
// can you actually afford this purchase?
if (amount > bank_balance) {
console.log(
"You can't afford this purchase. :("
);
}
// You can't afford this purchase. :(
My issue is that it does not matter if I change the value of bank_balance to a higher value, but it keeps printing : You can't afford this purchase.
I have try to make it so it does not print : You can't afford this purchase.
I can't make it work. I'm starting to think that the program is wrong, but I think is just me.
I know the solution is simple but I cant see it nor find it.
It comes from your while(amount < bank_balance). You increase amount until it's bigger than bank_balance. So obviously, it's bigger than bank_balance after that.
Also, you can use the developer tools available in every modern browser (F12 for Chrome or Firefox will open them), where you can put break points and follow your code's flow.
I don't know what the program is meant to do but it doesn't seem to make much sense to me.
It "buys" phones as long as you have money, but doesn't check if you have enough money for an additional phone.
So in the end of the while loop you have spend exactly your whole money on phones or (much more likely) spend more money than you have.
On top of this there are accessorizes and taxes. So in the end, you won't ever be able to afford your purchase.
And no matter how high you raise you balance, the program is written to exceed it.
The programm would work probably better with the line
while (amount + PHONE_PRICE + calculateTax(amount + PHONE_PRICE) <= bank_balance)
or even
while (amount + PHONE_PRICE + ACCESSORY_PRICE + calculateTax(amount + PHONE_PRICE + ACCESSORY_PRICE)<= bank_balance)
Although I have to admit that I'm not sure what the purpose of the SPENDING_THRESHOLD is.
You keep adding new phones and accessories until it reaches the total amount. I guess total cost becomes very close to the amount hence when you add the tax on top of that it crosses the limit and you see that message. I would suggest you to compare(in the while loop) the phone price along with the tax. Something like:
while (amount + PHONE_PRICE + calculateTax( PHONE_PRICE ) < bank_balance) {
// buy a new phone!
amount = amount + PHONE_PRICE + calculateTax( PHONE_PRICE );
// can we afford the accessory?
if (amount < SPENDING_THRESHOLD) {
amount = amount + ACCESSORY_PRICE;
}
}
Refer https://jsfiddle.net/Lxwscbbq/
Open the browser console to see the messages.
Program is not wrong it is simple:
var bank_balance = 303.91;
which is global. Suppose you provided
amount = 200;
amount = amount + calculateTax( amount );
amount = 200 + calculateTax(200);
if you check condition and you can see amount is grater than entered amount. Thats why you are getting "You can't afford purchase"
if (amount > bank_balance) {
console.log(
"You can't afford this purchase. :("
);
}
this is continuation of last successful topic
jquery: percentage of two numbers
First of all I want to thank you for your prompt support of previuous post.
Now I would like to make my script a little bit more complicated. I want to achive the following: If I insert PRICE1 and PRICE2 to have RATE between THEM, then I can change the RATE with other value and PRICE2 to change to the corespondent value according to RATE value.
My script of calculation is close to be correct, but my low knowledge about JQuery make me to ask you where I do something wrong.
Thank you for your support!
<script src="libs/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#PRICE1, #PRICE2").change(function() {
var result = parseFloat(parseFloat($("#PRICE1").val(), 10) - parseFloat($("#PRICE1").val(), 10))/ parseFloat($("#PRICE2").val(), 10) * 100;
$('#RATE').val(result||'');
})
else {
$("#PRICE1, #RATE").change(function() {
var result = parseFloat(parseFloat($("#PRICE1").val(), 10) * parseFloat($("#RATE").val(), 10))/ 100 + parseFloat($("#PRICE1").val(), 10);
$('#PRICE2').val(result||'');
})}
});
</script>
EDITED:
THE CODE ALMOST WORKING CORRECTLY WHICH MIGHT HELP OTHERS:
$(document).ready(function(){
$("#priceOne, #priceTwo").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var priceTwo = parseFloat($("#priceTwo").val());
$('#Rate').val((priceTwo - priceOne) / priceOne * 100); // Set the rate
});
// If price one or the rate is changed, adjust price two.
$("#priceOne, #RATE").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var rate = parseFloat($("#Rate").val());
$('#priceTwo').val((priceOne * rate)/ 100 + priceOne);
});
})
Thank you everyone who help me!!!
There is a else and no matching if. I'm not sure what you're trying to achieve, but some condition needs to be checked.
I'm going to try and code what it appears you need. But I'm going to rename your variables, not only because allcaps are hard to type, but unless it's a constant or a macro, they shouldn't be used.
// In ready() callback
// #NOTE - This does NO error checking for division by 0 or other NaN operations.
// If price two is changed, adjust the rate.
$("#priceTwo").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var priceTwo = parseFloat($(this).val());
$("#rate").val(priceTwo / priceOne); // Set the rate
});
// If price one or the rate is changed, adjust price two.
$("#rate #priceOne").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var rate = parseFloat($("#rate").val());
$("#priceTwo").val(priceOne * rate);
});
There are a few things about your code that needs attention:
parseFloat doesn't take a radix argument, the 10 you pass it is ignored.
parseFloat(parseFloat(... is pointless, I'm not sure why you've done this.
Don't use jQuery to select the same element multiple times in the same scope. Save the value and re-use it - save yourself some cycles.
As I mentioned, don't name your variables in all capitals unless they are some sort of constant that should never be changed, it's good to have clean style habits.
The basis of the assignment is to use the if/else if statements to set up the script. I need a little help finishing up the if/else part and for someone to look over any errors. Here's the assignment:
Write the JavaScript code in one HTML document using IF, and IF/Else statements for the following three situations. For each one make sure to write comments for each section.
Determine tax rate based on income and what the tax would be on the income.
Variable declarations section
1. Declare a variable that holds the income amount entered by the user.
2. Declare a variable that holds the minimum income that will not be charged taxes.
3. Declare a variable that holds the tax percentage for tax bracket 1.
4. Declare a variable that holds the tax percentage for tax bracket 2.
5. Declare a variable that holds the highest income for tax bracket 1.
6. Declare a variable that holds the highest income for tax bracket 2.
Assignments section
7. Assign $1500 as the highest income amount that will not be charged taxes.
8. Assign the highest income for tax bracket 1 to be $25K and the tax percent to 15%. Anything over $25K is in the next tax bracket.
9. Assign the highest income for tax bracket 2 to be $40K and the tax percent to 20%. Anything over $40K is in the next tax bracket.
10. Ask the user to enter a dollar amount.
11. Convert the data entered into a number.
Logic and Output section
12. Use only variables in your logic.
13. Determine whether or not the dollar amount entered is taxable.
14. Determine whether or not the dollar amount is in tax bracket 1 or 2.
15. Calculate the amount of tax on the dollar amount and display a message that tells the user what the tax amount would be on the number they entered.
16. For amounts greater than $40k display the message “I do not have the data to calculate the tax on this income.
Testing: Try values that are equal to the highest income for each bracket and the highest income for no taxes. Try numbers greater than the 40,000. Try amounts like 25,001 or 40,001.
My code thus far:
<script type="text/javascript">
// variable declarations
var userIncome;
var minIncomeNoTax;
var taxPercentBrack1;
var taxPercentBrack2;
var hiIncomeBrack1;
var hiIncomeBrack2;
var currentTaxBracket;
// Assignments
userIncome = prompt("Please enter your income in dollar amount.","");
minIncomeNoTax = 1500;
taxPercentBrack1 = 15/100;
taxPercentBrack2 = 20/100;
hiIncomeBrack1 = 25000;
hiIncomeBrack2 = 40000;
// Calculations & Output
if (userIncome >=minIncomeNoTax && userIncome <=hiIncomeBrack2)
{
alert("Your income is taxable.");
}
else if (userIncome >=minIncomeNoTax && userIncome <=hiIncomeBrack1)
{
alert("Your income amount is in tax bracket 1.");
}
else if (userIncome >hiIncomeBrack1 && userIncome <=hiIncomeBrack2)
{
alert("Your income amount is in tax bracket 2.");
}
else
{
alert("Sorry, I do not have the data to calculate the tax on this income.");
}
// output
document.write("Your Income: $" +userIncome + "<br />");
</script>
I fixed your if/else statement, and it seems to work now. I put it on jsfiddle:
http://jsfiddle.net/gXQXG/13/
Your issue was
if (userIncome <=1500 && userIncome >=40000)
else if (userIncome <=1500 && userIncome >=25000)
else if (userIncome <=25001 && userIncome >=40000)
The second statement in all three should be <=
A number cannot be both less than 1500 and greater than 4000 ;)
Next Step
You should replace the constants 1500, 25000, and 40000 with the variables you declared, hiIncomeBrack1 and hiIncomeBrack2
Lastly, there is one more issue in your logic, but, I will let you find that one. It has to do with two of the <= needing to actually be a <
Updated Code
// variable declarations
var userIncome;
var minIncomeNoTax;
var taxPercentBrack1;
var taxPercentBrack2;
var hiIncomeBrack1;
var hiIncomeBrack2;
var currentTaxBracket;
var totalTaxDue;
// Assignments
userIncome = prompt("Please enter your income in dollar amount.", 0);
minIncomeNoTax = 1500;
taxPercentBrack1 = 15 / 100;
taxPercentBrack2 = 20 / 100;
hiIncomeBrack1 = 25000;
hiIncomeBrack2 = 40000;
// Calculations & Output
if (userIncome >= minIncomeNoTax && userIncome <= hiIncomeBrack2)
{ //The user's income falls within our range of knowledge.
alert("Your income is taxable.");
if (userIncome >= minIncomeNoTax && userIncome < hiIncomeBrack1)
{ //The user falls into our first bracket
alert("Your income amount is in tax bracket 1.");
currentTaxBracket = taxPercentBrack1;
}
else if (userIncome >= hiIncomeBrack1 && userIncome <= hiIncomeBrack2)
{ //The user falls into our second bracket
alert("Your income amount is in tax bracket 2.");
currentTaxBracket = taxPercentBrack2;
}
}
else
{ //Can't help this user, they are not within our limits.
alert("Sorry, I do not have the data to calculate the tax on this income.");
}
//Figure out the actual amount due
//Need to use parseInt to convert from string to int.(User types a string into the prompt.)
totalTaxDue = currentTaxBracket * parseInt(userIncome);
// output
document.write("Your Income: $" + userIncome + "<br />");
//Multiply the decimal tax rate by 100 so we can print out a nice and clean %.
document.write("Your Tax Percent: " + (currentTaxBracket * 100) + "%<br />");
document.write("Pay Uncle Sam: $" + totalTaxDue + "<br />");