I am working on mortguage calculator and facing problem when the years value get bigger than it give me infinity in console and nan in result.
// principle / initial amount borrowed
var p = housePriceValue;
// calculate interest rate final value
var interestRateValueByAnum = interestRateValue / 12
var interestRateValuePercentByMonth = interestRateValueByAnum / 100
var i = interestRateValuePercentByMonth.toFixed(4)
var n = numberOfYears * 12
fha.value = p * i * (Math.pow(1 + i, n)) / (Math.pow(1 + i, n) - 1)
Question:
How do I calculate the compound interest when the underlying interest rate is also increasing by a constant growth rate (e.g. 10%) annually?
Example: $1000, interest rate 5% annually, for a period of 5 years. This how I would calculate the compound interest:
Compound Interest
let principal = 1000;
let n = 1; let t = 5; let rate = 10; let r = rate/100;
let compoundInterest = principal*Math.pow((1+r/n),nt);
But now I actually want the rate itself to increase by 10% each year after the first year has passed.
First year: 5%
Second year: 5% + (5 * 0,1) = 5,5%
Third year: 5,5% + (5,5 * 0,1) = 6,05%
Given the starting conditions:
let startingPrincipal = 1000;
let numberOfYears = 5;
let startingRate = 10;
let rateIncreaseRate = 10;
You can calculate the interest yearly for each of the years, feeding it the updated balance, and new interest rate. I simplified the formula since you have yearly compounding and the calculation for each period is just 1. Let me know if you want to be able to compound differently within the year.
let yearlyInterest = startingRate;
let currentBalance = startingPrincipal;
for (let i = 0; i < numberOfYears; i++) {
currentBalance *= 1 + yearlyInterest / 100;
yearlyInterest *= 1 + rateIncreaseRate / 100;
}
console.log(currentBalance);
Output:
1777.9906868317107
Which you can round or trunc as needed by your requirements.
I've built a form, it works out a total, then another total, takes 4% away from the total and then gives the final value.
My issue is that i do not receive the decimal places to the calculation, so for example if the total price is £500 and the 4% removal is $52.10 my total value is 53, not 52.10.
JSFiddle: https://jsfiddle.net/znc93w90/1/
jQuery(document).ready(function(){
var insOn = 15;
var insOff = 0;
var insuranceCover = 0;
var qtyy=jQuery("#wpforms-2562-field_5");
var completetotal=jQuery("#totaltwo");
qtyy.keyup(function(){
//NewValue = 4% of the total
var newValue = parseInt(completetotal.val()) * 0.04;
//FinalValue = Total - 4% - 25
var finalValue = parseInt(completetotal.val()) - parseInt(newValue) - 25;
//Spit the totals out
jQuery('#totalfinal').text(finalValue.toFixed(2));
jQuery('#testing').text(newValue.toFixed(2));
jQuery('#testingtwo').val(finalValue.toFixed(2));
});
});
Just don't parse your numbers to an Int:
//NewValue = 4% of the total
var newValue = completetotal.val() * 0.04;
//FinalValue = Total - 4% - 25
var finalValue = completetotal.val() - newValue - 25;
I have a number which I need to divide into 5 parts. However, I want each part to be a random number. But when all the parts are added together, they equal the original number. I am unsure of how to do this with JavaScript. Furthermore, I don't want the min of the divided parts to be 0 or 1, I want to set the min myself.
For example, the number is 450. I want the divided parts to be no less than 60. So to start, the array would be [60,60,60,60,60]. But I want to randomize so that they all add up to 450. What would be the best way to go about doing this?
Thank you!
This is what I've tried so far:
let i = 0;
let number = 450;
let numArray = [];
while(i <= 5){
while(number > 0) {
let randomNum = Math.round(Math.random() * number) + 1;
numArray.push(randomNum);
number -= randomNum;
}
i += 1;
}
let your number be N, and let pn be the nth part. To get 5 parts:
p1 = random number between 0 and N
p2 = random number between 0 and N - p1
p3 = random number between 0 and N - p2 - p1
p4 = random number between 0 and N - p3 - p2 - p1
p5 = N - p4 - p3 - p2 - p1
Edit 2017
To make it seem more random, shuffle the numbers after you generate them
Edit 2020
I guess some code wouldn't hurt. Using ES7 generators:
function* splitNParts(num, parts) {
let sumParts = 0;
for (let i = 0; i < parts - 1; i++) {
const pn = Math.ceil(Math.random() * (num - sumParts))
yield pn
sumParts += pn
}
yield num - sumParts;
}
Fiddle Link
Sum the five minimums (eg min = 60) up:
var minSum = 5 * min
Then get the difference between your original number (orNumber = 450) and minSum.
var delta = orNumber - minSum
Now you get 4 different random numbers in the range from 0 to exclusive 1.
Sort these numbers ascending.
Foreach of these randoms do the following:
Subtract it from the last one (or zero for the first)
Multiply this number with the delta and you get one of the parts.
The last part is the delta minus all other parts.
Afterwards you just have to add your min to all of the parts.
This function generates random numbers from 0 to 1, adds them together to figure out what they need to be multiplied by to provide the correct range. It has the benefit of all the numbers being fairly distributed.
function divvy(number, parts, min) {
var randombit = number - min * parts;
var out = [];
for (var i=0; i < parts; i++) {
out.push(Math.random());
}
var mult = randombit / out.reduce(function (a,b) {return a+b;});
return out.map(function (el) { return el * mult + min; });
}
var d = divvy(450, 6, 60)
console.log(d);
console.log("sum - " + d.reduce(function(a,b){return a+b}));
You can use a do..while loop to subtract a minimum number from original number, keep a copy of original number for subtraction at conclusion of loop to push the remainder to the array
let [n, total, m = n] = [450, 0];
const [min, arr] = [60, []];
do {
n -= min; // subtract `min` from `n`
arr.push(n > min ? min : m - total); // push `min` or remainder
total += arr[arr.length - 1]; // keep track of total
} while (n > min);
console.log(arr);
To randomize output at resulting array select a number greater than min and less than n to create a random number within a specific range
let [n, total, m = n] = [450, 0];
const [min, arr, range = min + min / 2] = [60, []];
do {
let r = Math.random() * (range - min) + min; // random number in our range
n -= r; // subtract `min` from `n`
arr.push(n > min ? r : m - total); // push `r` or remainder
total += arr[arr.length - 1]; // keep track of total
} while (n > min);
console.log(arr);
I made a longer version for beginners.
const n = 450;
const iterations = 5;
const parts = [];
// we'll use this to store what's left on each iteration
let remainder = n;
for (let i = 1; i <= iterations; i += 1) {
// if it's the last iteration, we should just use whatever
// is left after removing all the other random numbers
// from our 450
if (i === iterations) {
parts.push(remainder);
break;
}
// every time we loop, a random number is created.
// on the first iteration, the remainder is still 450
const part = Math.round(Math.random() * remainder);
parts.push(part);
// we must store how much is left after our random numbers
// are deducted from our 450. we will use the lower number
// to calculate the next random number
remainder -= part;
}
// let's print out the array and the proof it still adds up
const total = totalFromParts(parts);
console.log(parts);
console.log('Total is still ' + total);
// this function loops through each array item, and adds it to the last
// just here to test the result
function totalFromParts(parts) {
return parts.reduce((sum, value) => sum + value, 0);
}
There are much more efficient ways to code this, but in the interest of explaining the logic of solving the problem, this walks through that step by step, transforming the values and explaining the logic.
// Set start number, number of fragments
// minimum fragment size, define fragments array
var n = 450
var x = 5
var minNumber = 60
var fragment = n / x
// stuff array with equal sized fragment values
var fragments = []
for (i = 0; i < x; i++) {
fragments[i] = fragment;
}
document.write("fragments: " + fragments);
var delta = [];
// iterate through fragments array
// get a random number each time between the fragment size
// and the minimum fragment sized defined above
// for even array slots, subtract the value from the fragment
// for odd array slots, add the value to the fragment
// skip the first [0] value
for (i = 1; i< x; i++) {
delta[i] = Math.floor(Math.random() * (fragment - minNumber));
document.write("<br />delta: " + delta[i]);
if((i % 2) == 1) {
fragments[i] -= delta[i]
}
else {
fragments[i] += delta[i]
}
}
// set the initial fragment value to 0
fragments[0] = 0
// defines a function we can use to total the array values
function getSum(total, num) {
return total + num;
}
// get the total of the array values, remembering the first is 0
var partialTotal = fragments.reduce(getSum)
document.write("<br />partial sum: " + partialTotal);
// set the first array value to the difference between
// the total of all the other array values and the original
// number the array was to sum up to
fragments[0] = (n - partialTotal)
// write the values out and profit.
document.write("<br />fragments: " + fragments);
var grandTotal = fragments.reduce(getSum)
document.write("<br />Grand total: " + grandTotal);
https://plnkr.co/edit/oToZe7LGpQS4dIVgYHPi?p=preview
I'm trying to apply a discount to a selection in JavaScript, but for some reason, my code is returning the total to subtract as the total price:
selectone = parseInt(selectone);
var textarea = document.getElementById('discount');
var word = '15off';
var textValue=textarea.value;
if (textValue.indexOf(word)!=-1)
{
var discval = parseFloat(selectone);
var num = parseInt(discval);
var retval = num - (num * .15);
} else {
var retval = 0
}
var total = selectone - retval;
document.getElementById("rettotal").innerHTML = "Price starts from £" + total;
}
For example, if something costs £100 and a 15% discount is applied, the total will be '£15' instead of '£100' ('retval' instead of 'total')
Is there something I've missed in this, or is something missing?
I've not done maths in JavaScript much so a bit over my head!
Many thanks
You've logic problem in math part.
You want to get amount after discount.
You're doing it:
var retval = num - (num * .15); // 100 - (100 * .15) = 85
But after You're removing discount from amount:
var total = selectone - retval; // 100 - 85 = 15
So here is the fix:
var price = parseFloat(selectone);
var discount = (textValue.indexOf('15off') != -1)?
price * .15
: 0;
var total = price - discount; // 100 - 15 = 85
or just be simple (if discount applies once):
var total = parseFloat(selectone);
if(textValue.indexOf('15off') != -1) {
total *= .85;
}
let's be flexible (applying multiple discounts to price):
var textValue = 'take this 15off and this 10off';
var price = parseFloat(1000);
var total = price;
total-= (textValue.indexOf('15off') != -1)?
price * .15
: 0;
console.log(total);
total-= (textValue.indexOf('10off') != -1)?
price * .15
: 0;
console.log(total);
Because... math.
selectone = parseInt(selectone);
...
var discval = parseFloat(selectone); // doesn't change the things, it's an int already
var num = parseInt(discval); // so num is essentially discval, which is selectone
var retval = num - (num * .15); // here you get 85% of num...
...
var total = selectone - retval; // here you get 15% back
The fix is to remove num - from retval, so as var retval = num * .15;
The code you've shown could be compressed to this:
var textarea = document.getElementById('discount');
var total = parseFloat(selectone)*(1-0.15*textarea.value.includes("15off"));
document.getElementById("rettotal").innerHTML = "Price starts from £" + total;
Or, if you have problems with includes() not being supported by your browser (in case it's IE), you could also use match():
var total = parseFloat(selectone)*(1-0.15*(textarea.value.match("15off")|0));
You have a JavaScript operator precedence and meaning problem there. That's syntax mistake on your part.
In an expression like this:
x - y = z
You are thinking that:
z = x - y //but it's not.
What you are really saying is:
y = z and x = x - z