Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
My Javascript formula is
total = parseFloat(unit * rate) +
parseFloat(rateamount) +
parseFloat(((unit * rate) +
(rateamount)) * (tax/100));
values are:
unit = 5, rate = 10, rateamount = 10, tax = 10.
The answer it is giving me is 561, which is wrong.
Any help is welcome.
Your problem is that you are concatenating strings with this part:
parseFloat(((unit * rate) + (rateamount))
You forgot to parse rateamount which is a string of '10'.
So this Code:
var unit = '5',
rate = '10',
rateamount = '10',
tax = '10';
var total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + (rateamount)) * (tax / 100));
console.log(total);
should be like that:
var unit = '5',
rate = '10',
rateamount = '10',
tax = '10'
var total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + parseFloat(rateamount)) * (tax / 100));
console.log(total);
Though i wouldn't use parseFloat like that, i would just do it once before any calculations, in order to stay away from bugs like this one.
var unit = '5',
rate = '10',
rateamount = '10',
tax = '10';
var parsedUnit = parseFloat(unit),
parseRate = parseFloat(rate),
parsedRateamount = parseFloat(rateamount),
parsedTax = parseFloat(tax);
var total = parsedUnit * parseRate + parsedRateamount + ((parsedUnit * parseRate) + (parsedRateamount)) * (parsedTax / 100);
console.log(total);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am writing some JS and I can't seem to figure out how to write a function that will give a true or false statement back.
The way I want to write it is:
Loop function 5 times
on each loop give 1 of 8 random prizes
then check the probability of getting the prize, e.g 1 out of 10,000.
One of the loops has to provide with 1 as true
Any help is appreciated.
This is what I have tried, in terms of getting the probability
function prob(n) {
var old = n - 1;
var val = (n += 1);
return Math.floor(Math.random() * val) == old;
}
console.log(prob(2));
I generally use these helper functions if I need random
const chance = (percentage) => Math.random() * 100 < percentage;
const getRandomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const getRandomArbitrary = (min, max) =>
Math.random() * (max - min) + min;
console.log(chance(50));
console.log(getRandomInt(1, 10));
console.log(getRandomArbitrary(0, 5));
// Full code
const prizes = [{
name: 'Bear',
probability: 5,
},
{
name: 'Car',
probability: 0.02,
},
{
name: 'Poster',
probability: 90,
},
];
let count = 5;
while (count--) {
const prize = prizes[getRandomInt(0, prizes.length - 1)];
const win = chance(prize.probability);
console.log(`Prize: ${prize.name} - Won: ${win}`);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
i tried a few ways to get a random number from 1 to 10 and all return undefined or NaN why ?
here is what i tried
var num = Math.floor(Math.random * 10)
function getNum() {
return Math.floor(Math.random * 10);
}
var num2 = getNum();
console.log('num = ' + num + 'num2 = ' + num2);
both dosn't give a number when logged
You need to actually invoke Math.random if you intend for it to generate the random number (ie Math.random())
var num = Math.floor(Math.random() * 10)
function getNum() {
return Math.floor(Math.random() * 10);
}
var num2 = getNum();
console.log('num = ' + num + 'num2 = ' + num2);
Math.random is a method, not a property, so you need to call it as Math.random(). You are also missing a semicolon after your first line.
As stated by #kloddant Math.random is method so you forgot the parentheses ().
So here's the snippet of how you can implement it
var num = Math.floor(Math.random() * Math.floor(10))
function getNum() {
return Math.floor(Math.random() * Math.floor(10));
}
var num2 = getNum();
console.log('num = ' + num + 'num2 = ' + num2);
I am working on a calculator that calculates simple interest and compounding interest. All good, with the simple interest, but I can't seem to be able to solve the problem with the compounding interest, using a loop. I need a loop, because pushing the data into an array to use it in a chart later.
I have the formula from here: https://www.moneysmart.gov.au/managing-your-money/saving/compound-interest
I am using this as reference: https://www.bankrate.com/calculators/retirement/roi-calculator.aspx
The code is in work here: http://www.course0001.com/fiverr/iddqd
I have this so far(updated):
// Inputs from user:
// Initial deposit (starting balance)
// Number of years
// Interest
// Frequent Deposit amount
// Deposit and compound frequency (monthly, weekly, yearly)
// Calculations
var investedCapitalArray = [];
var simpleInterestArray = [];
var compoundInterestArray = [];
var compoundPrincipal = 0;
var years = [];
var accumulatedInvestment;
function calculate() {
years = [];
let interest = rateNumeric.getNumber() / 100; // annual interest rate
let additionalDeposit = additionalNumeric.getNumber(); // Regular deposit
let frequency = freqInput.value; // Frequency of regular deposit
let initialDeposit = initialNumeric.getNumber();
let taxRate = taxNumeric.getNumber();
// Invested captal amount first year
investedCapitalArray = [];
investedCapitalArray.push(initialDeposit + (frequency * additionalDeposit));
// simple interest first year
simpleInterestArray = [];
simpleInterestArray.push((investedCapitalArray[0] * ( (interest) / 100)) * (1 - taxRate));
// compund interest first year
compoundInterestArray = [];
let firstYearInvestment = investedCapitalArray[0]; // First deposit + regular deposits in first year
for (let i = 1 ; i < yearsInput.value ; i++) {
// Invested capital over the years (correct results)
investedCapitalArray.push( (investedCapitalArray[i-1]) +
(frequency * additionalDeposit) );
// simple interest over the years (correct results)
simpleInterestArray.push( simpleInterestArray[i-1] +
((firstYearInvestment +
((frequency) * additionalDeposit) * i ) * interest) );
// compound interest over the years (incorrect results)
compoundInterestArray.push( investedCapitalArray[i-1] *
Math.pow(1 + interest / 100, i) - initialDeposit);
years.push('Year' +i);
}
}
The issue is with the paranthesis you should use (investedCapitalArray[i - 1] + compoundInterestArray[i - 1]) * (1 + 0.07). Thanks
I think the problem is with unboxing the object. Try this:
compoundInterestArray.push( compoundInterestArray[i-1] + (parseInt(investedCapitalArray[i-1]) + parseInt(simpleInterestArray[i-1])) * ( rateNumberic.getNumber() / 100)) );
Thank you everyone for the inputs, after thoroughly researching the compounding interest topic, I wrote an algorithm that works perfectly. It's actually quite simple.
My algorithm is based on this explanation:
"What Is Compound Interest? Compound interest (or compounding interest) is interest calculated on the initial principal, which also includes all of the accumulated interest of previous periods of a deposit or loan."
Therefore it works like this in a loop:
compoundInterest += (((simpleInterestArray[i - 1] + compoundInterest) * (interest));
Full code below.
for (let i = 1; i < yearsInput.value; i++) {
// Invested capital over the years (works fine)
investedCapital = (investedCapitalArray[i - 1]) +
(frequency * additionalDeposit);
investedCapitalArray.push(investedCapital);
// imple interest over the years (works fine)
simpleInterest = simpleInterestArray[i - 1] +
((firstYearInvestment + (frequency * additionalDeposit) * i) * interest);
simpleInterestArray.push(simpleInterest);
// compound interest over the years (correct results)
compoundInterest += (((simpleInterestArray[i - 1] + compoundInterest) * (interest)));
compoundInterestArray.push(compoundInterest);
}
I'm trying to create a function that returns the money I have after x years of interest.
var calculateInterest = function(total, year, rate) {
(var interest = rate / 100 + 1;
return parseFloat((total * Math.pow(interest, year)).toFixed(4))
}
console.log(calculateInterest(915, 13, 2));
I'm not getting it to work and I'm stuck!
Any advice?
You were close. You don't need parentheses around var interest:
var calculateInterest = function(total, year, rate) {
var interest = rate / 100 + 1;
return parseFloat((total * Math.pow(interest, year)).toFixed(4));
}
var answer = calculateInterest(915, 13, 2);
console.log(answer);
I'd recommend cleaning it up a little to:
var calculateInterest = function(total, years, ratePercent, roundToPlaces) {
var interestRate = ((ratePercent / 100) + 1);
return (total * Math.pow(interestRate, years)).toFixed(roundToPlaces);
}
var answer = calculateInterest(915, 13, 2, 2);
console.log(answer);
You don't need parseFloat() if the variable is already a number (it's needed when you're parsing from a string, which is not the case here). I am adding a parameter to specify how many decimal places to round to is useful so you can control the output of the function.
Updated fiddle
I am creating a "whack-a-mole" style game for primary school children where they have to click on the correct number in correspondence to the sum given.
At the moment the program is generating addition sums like this.
function createPlusSum(total) {
console.log(total)
var int1 = Math.ceil(Math.random() * total);
var int2 = total - int1;
$('#target').html(int1 + ' + ' + int2 + ' = ?');
}
I have done this again for subtraction and it works, but I don't know where to go from here in regards to randomizing whether an addition or subtraction question is produced. Here is the function to produce a subtraction question.
function createTakeSum(total) {
console.log(total)
var int1 = Math.ceil(Math.random() * total);
var int2 = total + int1;
$('#target').html(int2 + ' - ' + int1 + ' = ?');
}
I use this to create the addition sums
createPlusSum(total);
How would I say I want
createPlusSum(total);
or
createTakeSum(total);
Try this:
function createSum() {
total = Math.ceil(Math.random() * 10);
if(Math.random() > 0.5)
{
createTakeSum(total);
} else {
createPlusSum(total)
}
}
I would use random numbers again:
var rand = Math.floor(Math.random()*2);
switch (rand) {
case 0:
createPlusSum(total);
break;
case 1:
createTakeSum(total);
break;
}
I am not suggesting that this is how you should do it, but I am merely providing an alternative answer for thoroughness. (Pardon me, if the code is wrong. I'm a bit rusty with JS.
{
0: createPlusSum,
1: createTakeSum
}[Math.floor(Math.random() * 2)](total);
you can assign functions to array fields and call them random.
var func = new Array();
func[0] = function createPlusSum(total) {....};
func[1] = function createTakeSum(total) {....};
var rand = Math.floor(Math.random() * func.length);
func[rand](total);
this should do the trick, plus you can add as many functions as you want, just append them to the "func"-array
Here's a script that creates a random "add" or "subtract" question within the given range, and posts the correct answer in the console.log:
<div id="target"></div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var total = {low: 10, high: 30}; // range
jQuery(document).ready(function() {
var total = Math.floor(Math.random() * (total.high - total.low) + total.low);
var int1 = Math.floor(Math.random() * total);
var int2 = total - int1;
if (Math.random() > 0.5) { // add
var question = int1 + ' + ' + int2 + ' = ?';
var answer = total;
}
else { // subtract
var question = total + ' - ' + int1 + ' = ?';
var answer = int2;
}
$('#target').html(question);
console.log('Correct answer: ' + answer);
});
</script>
Here's the working jsFiddle example