Trying to create a loan calculator based on two sliders. I feel I'm nearly there but the syntax is letting me down plus one last formula.
I have two sliders, one which represents the loan amount, the other represents the loan length.
Here is a bit of the code to highlight all the calculations. I think there are errors here too.
function update() {
$amount = $("#slider1").slider("values", 100);
$interest = $amount / 100 * 15 ;
$perday = 15 ;
$apr = (($interest / $amount) / ("#slider2"/365) * 10000) / 100;
$amount2 = $amount + $interest;
$("#amount").val($amount1);
$("#amount2").val($amount2);
$("#amount3").val($interest);
}
Interest is charged at 15% of the amount borrowed.
Each day is worth 15p so in order to get my final charge.
[15% of the loan amount total]
– [0.15p per day credit]
I have developed a fiddle but its not correct, hence why I'm here.
Fiddle Here
How can I get both the sliders to work together so that if I move the top or bottom slider, it will affect the overall loan amount and Interest?
Any help will be most appreciated. I'm really struggling with this one.
I believe this is what you want - jsfiddle <- follow link
function update() {
$interest = 0.15 ;
$perday = 15 ;
$amount1 = $("#amount").val();
$dayscount = $("#days").val();
$amount2 = parseInt($amount1) + $interest * parseInt($amount1) + (parseInt($dayscount) * ($perday/100));
$("#amount2").val($amount2);
$("#amount3").val(parseFloat($amount2-$amount1).toFixed(2));
}
Fixed your update algorithm and your slider handlers
I considered that you last 2 fields (Your Loan & Interest) are the final value to be paid and the difference between the value to be paid and the value borrowed respectively. If this interpretation is not what you intended please comment.
UPDATE 1
Here I updated the jsfiddle. Beware that I don't know what the APR is, so validate that my calculation are right. I also did not use any rounding, cause I don't know if you need it like this
UPDATE 2
Updated with new formula here. I still have no idea if this is right or not
If i understood you right, you could do something like this:
function update() {
var interest = 0.15;
var sliderAmount = parseFloat($("#slider1").slider("option", "value"));
var days = parseFloat($("#slider2").slider("option", "value"));
var perday = 15 * days ;
var interestAmount = sliderAmount * interest * days;
$("#amount1").val(sliderAmount);
$("#amount2").val(sliderAmount);
$("#amount3").val(interestAmount+ perday);
}
Related
I'm reading Kyle Simpson's YDKJS and this was the first exercise after the first chapter. We were to write a program that finds the value of a phone + tax and purchase a certain amount of phones + accessories below a given threshold.
A couple of questions.
1) Is there a way to call the toFixed method on a var without having to build it into a function? Meaning can I build that formatting function then just call it on a variable when I'm going to console.log it.
2) If I place 'moneyInBank = moneyInBank - amount;' into the loop, why does it spit out a negative number? Does this have to deal with scopes? Is it creating a new variable inside the loop instead of changing the balance at the global level?
I wanted to go slightly beyond what was required like.
- Stop the loop if adding 1 more phone breaks the threshold. Instead, it went above the threshold. In this case, do I need to use some type of remainder expression?
const spendingThreshold = 1500;
const priceOfPhone = 150;
const priceOfAcc = 20;
const salesTax = .08;
var moneyInBank = 2500;
var amount = 0;
function tax(amount) {
return amount * salesTax;
}
function costOfPhone(){
return(priceOfPhone + priceOfAcc) + ((priceOfPhone + priceOfAcc) * salesTax);
}
/* We are running a conditional using the 'while' loop to run when the amount is less than the var spendingThreshold.
We then change the amount variable by adding 'amount' + the costOfPhone. costOfPhone takes in the price of the phone + taxes already, so there is no need for a taxes function. However, if we wanted to we could create a taxFunction
to be called on other products as well and not just on the phones.
*/
while (amount < spendingThreshold){
amount = amount + costOfPhone();
if(amount > spendingThreshold)
console.log("You cannot afford another phone!");
}
function formatAmount(){
return "$" + amount.toFixed(2);
}
moneyInBank = moneyInBank - amount;
function formatMoneyBank(){
return "$" + moneyInBank.toFixed(2);
}
console.log("The cost of each phone + tax is $" + costOfPhone());
console.log("The cost of your total purcahase is " + formatAmount(amount));
console.log("You have " + formatMoneyBank(moneyInBank) + " left in your bank account!");
For your question number one, you may display monetary values in javascript like so:
moneyInBank.toLocaleString('en', {style: "currency", currency: "USD"})
This works for all variables whose type is 'number' and leverages the internationalization capabilities of your browser. Of course, you could also define
const format = funds => `$${Number(funds).toFixed(2)}`
and invoke it like so format(5) or even so format("6.0").
For your second question, there is no issue with scopes. You just need to revise the logic. In particular, the loop does not seem to break when the threshold is exceeded and does not require the bank account to have sufficient funds moneyInBank >= amount.
I'm not sure how to word the question and i'm still quite new at javascript.
So I've got a random quote generator that has each quote result as an array. I'd like to add in two items in the array which I've got so far but having one result be a random number generated eg "2 quote" but having 2 be randomised each time. The end result is for a browser based text game. So it could be "2 zombies attack" or "7 zombies attack." The code I have so far is:
var quotes = [
[x, 'Zombies attack!'],
[x, 'other creatures attack'],
['next line'],
]
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
Ideally need x(or i however it's going to work) to be the result of a random number between a set range, each differently each array.
Thank you
p.s I forgot to mention that not all the quotes require a number. Thats why I've done it as a double array.
If I understand your goal correctly, you want to have a set of similar-ish message templates, pick one of them at some point and fill it with data, correct? There's a lot of ways to tackle this problem, depending on how varying can your templates be. For a simple case in my head where you just need to prepend a number to a string I'd do something like this:
var messages = [" zombies attack",
" other creatures attack"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = numberOfMonsters + messages[messageIndex]; // construct a resulting message
document.getElementById('quote').textContent = result;
If you'd rather have more complex strings where you don't necessarily add a number (or any string) to the beginning, like ["There's X things in the distance", "X things are somewhere close"], then I'd recommend to either come up with some sort of string formatting of your own or use a library to do that for you. sprintf.js seems to be just right for that, it will let you do things like this:
var messages = ["%d zombies attack",
"A boss with %d minions attacks"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = sprintf(messages[messageIndex], numberOfMonsters) // format a final message
document.getElementById('quote').textContent = result;
EDIT: Your task is much more complex than what is described in the original question. You need to think about you code and data organization. You have to outline what is finite and can be enumerated (types of actions are finite: you can loot, fight, move, etc.), and what is arbitrary and dynamic (list of monsters and loot table are arbitrary, you have no idea what type and amount of monsters game designers will come up with). After you've defined your structure you can come up with some quick and dirty message composer, which takes arbitrary entities and puts them into finite amount of contexts, or something. Again, I'm sort of shooting in the dark here, but here's an updated version of the code on plunkr.
I solved it to do what I want and still have the numbers different. The issue was I should have had the number generator within the quote function. Also can create multiple variables to use too for different number generators. The plan is to then integrate it with php to add content dynamically. Which I can do. Thanks Dmitry for guiding me in the right direction.
function newQuote() {
var MonsterOne = Math.floor((Math.random() * 14) + 0);
var MonsterTwo = Math.floor((Math.random() * 14) + 0);
var MonsterThree = Math.floor((Math.random() * 14) + 0);
var MonsterFour = Math.floor((Math.random() * 14) + 0);
var quotes = [
['Test', MonsterOne, 'One'],
['Test', MonsterOne,'Two'],
['Test', MonsterThree, 'Three'],
[MonsterFour, 'Four'],
['Five'],
]
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
I run the following Excel function to calculate weekly re-payments.
CELL B4 = 15000
=(PMT(6.5%/12,60,(-B4),(0.2*B4),1))*12/52
Where 6.5% = rate, 60 = number of payments, 0.2*15000 = balloon and *12/52 is for calculating weekly repayments.
The output of the above is 57.62, however when coding it up in JS I end up with 77.11 as the result. After checking through it several times I can't seem to find where I've gone wrong.
Calculation for PMT is done as follows.
var q = Math.pow(1 + rate_per_period, number_of_payments);
return -(rate_per_period * (future_value + (q * present_value))) / ((-1 + q) * (1 + rate_per_period * (type)));
I've created a fiddle showing my PMT calculations.
Also, I am using an almost exact copy of the accepted answer in another question here on SO but mine varies slightly.
My mistake!
I was doing a negative on the PMT function instead of doing the negative on the PV (present value).
var payment = pmt(interest / 12, 60, -(present), future, beginning);
I'm trying to get the percentage between two numbers for the purpose of showing the difference as far as a discount. I've tried to simplify it as much as I can but I still cant get what I want.
Here is an example.
var RegPrice = 8.95;
var OnSale = 6.67;
var OnSaleAT = Math.abs(Math.max(100.00 - OnSale / RegPrice * 100.00));
alert(OnSaleAT.toFixed(2));
What I'm trying to get is the alert(); to return a value of 25.50. However, I'm getting 25.47.
Any ideas on how I can get this right?
25.47486... is the correct answer. If you're attempting to round to the nearest tenths, you can use:
var result = Math.round(OnSaleAT * 10) / 10;
Which outputs: 25.5 and from there you can format your answer how you like.
$(window).load(function() {
var RegPrice = 8.95;
var OnSale = 6.67;
var OnSaleAT = Math.round(Math.abs(Math.max(100.00 - 6.67 / 8.95 * 100.00)) * 10.00) / 10.00
alert(OnSaleAT.toFixed(2));
});
If you're trying to round to 25.5%, you can just alert with a toFixed param of 1 instead of 2:
alert(OnSaleAT.toFixed(1));
Other than that, Rob W is right...the math does come out to 25.47, and there's not much you can do about that.
try OnSaleAT.toFixed(1)+'0' :)
Math.ceil(1000* (1 - OnSale/RegPrice))/10
give you "25.5"
:)
I have a page on a site that calculates rate totals for a rental, which are optional. The javascript serves nothing more but to show you the updated total if you select or unselect checkbox options.
Here is what I've tried. It appears to work, but it is adding 2 cents to every other click for one of the checkboxes, I believe because toFixed rounds. How can I keep the number from rounding?
function update_rate(state, amount, field) {
if (state == true) {
rate = parseFloat($('span.rateTotal').text()) + amount;
rate = rate.toFixed(2);
due = parseFloat($('span.'+field).text()) + amount;
due = due.toFixed(2);
$('span.rateTotal').text(rate);
$('span.'+field).text(due);
} else {
rate = parseFloat($('span.rateTotal').text()) - amount;
rate = rate.toFixed(2);
due = parseFloat($('span.'+field).text()) - amount;
due = due.toFixed(2);
$('span.rateTotal').text(rate);
$('span.'+field).text(due);
}
}
Checkbox HTML:
<cfinput type="checkbox" name="linen_service" id="linen_service" checked="checked" value="0" onClick="update_rate(this.checked, #reservationQuery[7].xmlChildren[i]['dblAmount'].xmlText#, 'second-due');" />
Basically passes in the amount of the option, checkbox state, and the name of the field that should be affected.
Edit: Fiddle URL: http://jsfiddle.net/nGrVf/6/
Are you stuck with your your types?
I find it is almost always better to store monetary values in whole numbers of the lowest unit (e.g, cents, or pence) and then add the decimal point two places from the right when displaying.
So the conversions might look like:
var dollars = 100.43;
var cents = Math.round(dollars * 100);
//convert for display
var sCents = String(cents);
var display = sCents.substr(0, sCents.length-2) + "." + sCents.substr(sCents.length-2,2);
alert(display);
Can be seen here at http://jsfiddle.net/jameswiseman76/jhjtP/
Then you don't have to worry about any ugly floating point conversions.
The simplest solution I can think up is to round it down (using muls and floor): i.e.
rate = Math.floor(rate * 100)/100;
Edit: After a bit of testing, I found that there is nothing wrong with the given code. This means the calculation error comes from another part of the code or from the unknown amount variable.