Hi I need help creating a javascript calculator. Unfortunately, I'm not even sure how to search for an answer so I thought I would start here.
I need a calculator that multiplies a number based on an input. For example
Gross income
Number of Children 1, 2, 3, etc
If 1 child multiply gross income by 20%
if 2 multiply gross income by 25%
if 3, etc.
And then obviously it spits out a value.
I would really appreciate some guidance on where to go to try something like this out. Thanks in advance.
Try this:
var income = 100;
var children = 3;
var multiply = 0.15 + (children * 0.05);
var result = income*multiply;
As you required, I'll give you only some guidances to get this done. Indeed, it's pretty basic and you won't need us to give you the whole code.
Get the gross income value: http://www.javascript-coder.com/javascript-form/javascript-get-form.phtml
For the ratio, it depends on how you made the field:
Selectbox with key => value (for instance 1 => 0.20, 2 => 0.25): ratio = value
Textfield: ratio = 0.15 + value * 0.05
Then, calculation: result = ratio * grossIncome
var income = 100;
var children = 3;
var multiply = eval(0.15 + (children * 0.05));
var result = income*multiply;
use eval() for this,
If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
Related
I'm trying to get an array of numbers based on a calculation that keeps adding a set amount to the previous amount until this have repeated 20 times. The initial number is a negative number because the client pays an initial amount of money for a solar power system and then the calculation should subtract an amount each month based on how much the client saves by not having to pay for electricity. It needs to be an array (I think) because it needs to go into a chart. Here's a google worksheet that might make what I'm trying to more clear. The part of the sheet that is relevant to my question is in columns T and U in pink.
I did tonne of reading on loops, different array types (reduce and map). I'm new to this so it didn't seem any of those types of arrays will do what I need to be done. I found the below code somewhere and it seemed like this is the closest to what I need to happen but I could be completely off track (my adjusted version is further down):
// program to generate fibonacci series up to n terms
// take input from the user
const number = parseInt(prompt('Enter the number of terms: '));
let n1 = 0, n2 = 1, nextTerm;
console.log('Fibonacci Series:');
for (let i = 1; i <= number; i++) {
console.log(n1);
nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
}
I tried to adjust it to try get it to do what I need it to do but in console it shows one number and then the rest is NAN. I know this means not a number but I don't know why or how to fix it:
function runningNetProfit(n) {
var profitSequence = [0];
var nextYear = (monthlyEstimatedSavings * 12);
for (var i = negSystemCost; i < n - 1; i++) {
profitSequence.push(nextYear);
nextYear = nextYear + profitSequence[i];
}
return profitSequence;
}
console.log(runningNetProfit(20))
I added what I did (all of the code) to a codepen as well, maybe it can make my question more clear, that can be found here The javascript relevant to this question is right at the bottom from line 145. Any advice would be much appreciated.
See if this code works for you:
It takes a given installation cost, the price they pay for electricity, and the number of months, then spits out an array with these numbers.
const installCost = 250000;
const electricityCost = 45000;
const numMonths = 20
const newArray = Array.from({length: numMonths})
const updatedArray = newArray.map((_, index) => index * electricityCost - installCost);
console.log(updatedArray) // returns [-250000,-205000,-160000,-115000,-70000,-25000,20000,65000,110000,155000,200000,245000,290000,335000,380000,425000,470000,515000,560000,605000]
Here's the code sandbox for it: https://codesandbox.io/s/blue-pine-l5rjc8?file=/src/index.js
Ok, so I have very big array of numbers in javascript:
[1, 1.01, 1.02, 1.03, ..., 1.99, 2, ..., 9.98, 9.99, ..., 299.99, 300]
And what I need is to get one of them using random segment. So basically I need random number but the catch is that I need to get random using the lottery style. So the chance to get "1" will be 30 000 (very hight) and the chance to get 1.01 will be 29 999. But the chance to get 300 will be very low according of all numbers in this array.
I hope you will understand the problem and will help me to solve this. As I have mentioned before, this have to be made 100% randomly and I have no idea how to make it..
The solution I had so far:
I was trying to expanse the array by adding multiple same numbers and lower the count of it by each step. So I have added 30000 units of 1 and 29999 units of 1.01 ... and 2 units of 299.99 and one unit of 300. But the array got very large and I came here to find better solution.
Also I have found this: https://stackoverflow.com/a/13758064/5786106
and it seems to be the answer to me but I don't know how to use it with the decimal system (0.01, 0.02, ... 0.99)
var num = Math.pow(Math.floor(Math.random()*10), 2);
One solution would be to make the very large array you propose, but to make it imaginary, without ever constructing that object in code.
How long will the imaginary array be? Well your array has (300 - 1) * 100 + 1 = 29,901 elements in it. Then there are (29,901 + 1) * (29,901 / 2) = 447,049,851 elements in the imaginary array. So the first step is to generate a random integer between 0 and 447,049,850:
var imaginaryIndex = Math.floor(Math.random() * 447049851);
The next step is to determine which real index in your original array corresponds to the imaginaryIndex in the imaginary array.
var indexFromEnd = 0;
while((indexFromEnd + 2) * ((indexFromEnd + 1) / 2) < imaginaryIndex)
indexFromEnd++;
Finally, you need to calculate the value of the element in your array based on where it is in your array:
return 300 - (indexFromEnd * 0.01);
Now let's clean that up and put it in a nice, reusable function:
function triangularWeightedRandomSelect(myArray){
var imaginaryIndex =
Math.floor(Math.random() * (myArray.length + 1) * myArray.length / 2);
var indexFromEnd = 0;
while((indexFromEnd + 2) * ((indexFromEnd + 1) / 2) < imaginaryIndex)
indexFromEnd++;
return myArray[myArray.length - 1 - indexFromEnd];
}
I have a project I am working on and it needs to calculate mortgage calculations but I'm having trouble putting the formula into javascript.
the formula is:
M = P I(1 + I)^n /(1 + I )^n - 1
Any help is appreciated, thanks
P = loan princible
I = interest
N = Term
Break it down into a sequence of steps.
Multiplication is as straightforward as it gets: I*(1+I)
Division is the same: I/(1+I)
To the power of n is denoted by: Math.pow(3, 5); //3 to the power of 5
Math.pow() might be the only thing you didn't know yet.
Unrelated but useful,
Wrap your formula into a function and you have a mortgage-calculation function
calculateMortgage(p,i,n) {
result = //translate the formula in the way I indicated above
return result;
}
and call it like so:
var mortgage = calculateMortgage(300,3,2); // 'mortgage' variable will now hold the mortgage for L=300, I=3, N=2
Also, the formula you posted really doesn't make any sense - why is there a blank between P & I at the very beginning? Something's missing.
Try this: Math.pow(p*i*(1+i),n)/Math.pow(1+i,n-1)
Math.pow(a,2) is same as a^2
if P is not supposed to be with numerator then
this
p * (Math.pow(i*(1+i),n)/Math.pow(1+i,n-1))
or
p * (Math.pow((i+i*i),n)/Math.pow(1+i,n-1))
var M;
var P;
var I;
M = P*(Math.pow(I*(1+I),n)) / (Math.pow((1+I),n)-1);
Does this look right to you? I got the correctly styled formula from here.
Like what Nicholas above said, you can use functions to make it all the more easier.
var M;
function calculateMortgage(P, I, N){
M = P*(Math.pow(I*(1+I),n)) / (Math.pow((1+I),n)-1);
alert("Your mortgage is" + M);
}
And just call calculateMortgage(100, 100, 100); with your values for it to automatically give the answer to you.
Hello everyone! I have completed a couple of brief courses in JavaScript, and I have now moved on to Heads Up: JavaScript, which has been a lot of fun and is helping to cement my learning. I did run into something I didn't understand, though. In the following piece of code, I understand what the program generally does when it executes, but in attempting to trace each step of execution, I realized that I am confounded by the "What/Why/How" of a particular segment. Here's the code for the sample program I'm looking at:
function makePhrases() {
var words1 = ["24/7", "multi-tier", "30,000 foot", "B-to-B", "win-win"];
var words2 = ["empowered", "value-added", "oriented", "focused", "aligned"];
var words3 = ["process", "solution", "tipping-point", "strategy", "vision"];
var rand1 = Math.floor(Math.random() * words1.length);
var rand2 = Math.floor(Math.random() * words2.length);
var rand3 = Math.floor(Math.random() * words3.length);
var phrase = words1[rand1] + " " + words2[rand2] + " " + words3[rand3];
alert(phrase);
}
makePhrases();
This is the segment that has been confusing for me:
var rand1 = Math.floor(Math.random() * words1.length);
var rand2 = Math.floor(Math.random() * words2.length);
var rand3 = Math.floor(Math.random() * words3.length);
I get that it's the part of the code that randomizes which item from each array is chosen to form the new "random phrase", but I don't understand how it's doing so. I also hadn't known previously that Math.random or Math.floor could be applied to strings (must be because they're in an array, which is essentially a number?), or the how/why of using Math.random or Math.floor with strings.
Additionally, why do we need to use .length with this incarnation? What does it do? I appreciate your wisdom here, and taking the time to help someone who's new to coding, and still has so much to learn!
Let's look at the code:
var rand1 = Math.floor(Math.random() * words1.length);
Math.random() returns a number between 0 and 0.999999...
words1 is the list of words to choose from.
words1.length is the size of the list, the number of items, 5 in this case.
Math.random() * words1.length returns a number between 0 and 4.99999...
Finally use Math.floor() to get a whole number between 0 and 4.
This number is then used as an index in words1, so words1[rand1].
So the Math operations are never used on a string, fetching the string in only the last step.
All that's happening is Math.random() is being used as a multiplier against the number of elements in the respective arrays (the '.length' property) to create an index value. It isn't being applied to a string; just as part of an expression to determine an index into a string array.
You want to pick a random element from an array. So you need an index, in other words a random number from 0 to 4 (because your length is 5). Math.random will give you a random number between 0 and 1 (exclusive of 1). So to turn that into a random number between 0 and 4 you need to multiple by the length of 5.
Then, since we need an integer, not a floating point number, we use Math.floor to truncate it to a integer.
Math.random() //Return a random number between 0-1
words1.length() //Return the length of the array
Math.floor() //Return the closest integer less than or equal to a given number.
Now the expressions:
(Math.random() * words1.length)
Will return a random number between 0 and the length of the array. Could be a float, like 3,4 for example:
Math.floor(Math.random() * words1.length)
Will return an integer number between 0 and the length of the string, so you can use it now as the string (behaving like an array) indexer.
Note: Note that the random number is between 0 (inclusive) and 1 (exclusive), that's why is secure to use Math.floor(), to avoid an exception, and that's why is not used Math.ceiling.
I'm trying to create a basic profit calculator but I am struggling with one issue.
I've written some basic javascript and the formula almost works. However my issue is that the decimal point doesn't seem to want to work properly. For example:
What is the case cost: 2.80
How may units per case: 2
What is the sell price: 3.15
Total Profit = 1.75 Profit should of course be, 0.175
I'm a complete newbie to JavaScript so your help would be much appreciated.
<form id="profitCalculator">
<p><label>What is the case cost? <input type="text" name="casecost"></label></p>
<p><label>How many packs / units per case? <input type="text" name="packs"></label></p>
<p><label>What is the sell price? <input type="text" name="sell_price"></label></p>
<p>Total profit £: <input type="text" name="profit"></p>
document.getElementById('profitCalculator').onclick = function () {
var casecost = this.elements['casecost'].value || 0;
var packs = this.elements['packs'].value || 0;
var sell_price = this.elements['sell_price'].value || 0;
var profit = sell_price - casecost / packs;
this.elements['profit'].value = profit.toFixed(2); }
Thanks
It should be
var profit = (sell_price - casecost) / packs;
BUT - Never calculate currency with decimals in Javascript!
Javascript will truncate decimal values when they become to long, possibly resulting in nasty rounding errors. Always multiply your values by 100, then calculate everything, and at last, divide by 100 again.
Look at order of operations, you may know this as 'BODMAS'
Supporting Link: http://www.mathsisfun.com/operation-order-bodmas.html
Change to (sell_price - casecost) / packs;
your problem occurs because operators procedence.
var profit = sell_price - casecost / packs;
/ (division) occurs first than - (minus).
As your example.
2.80 / 2 = 1.4
3.15 - 1.4 = 1.75
You should put some parenthesis covering what has to priority, in your case, to get the value 0.175, you should put the like this.
(3.15 - 2.80) / 2 = 0.175
in code
var profit = (sell_price - casecost) / packs;
See MDN's reference on Operator Precedence and you'll see that division (and multiplication) is done before addition or subtraction. So you have essentially:
3.15 - (2.80 / 2) = 1.75
Instead of:
(3.15 - 2.80) / 2 = 0.175
Also note, as #Adrian Schmidt pointed out, using floating point numbers for math is a bad idea. If you do that above calculation in javascript you actually get:
0.17500000000000004
Because computers don't have infinite precision when representing floating point numbers. See, for example: Is floating point math broken?
So your formula should be:
(sell_price - casecost) / packs
Another thing to consider is that the values you get from your text boxes are strings, not numbers. Your formula works because there is no - operator for strings, so javascript automatically converts your values to numbers. But this is a dangerous thing to rely on. For example, if you did this:
sell_price + casecost
With your example inputs, the result would be:
"3.152.80"
Because it's doing string concatenation, not addition.
So it's worth using parseFloat to convert your strings. (and parseInt for packs as it is, presumably, an integer)
So a complete example might look like this:
var casecost = parseFloat(this.elements['casecost'].value) * 100 || 0;
var packs = parseInt(this.elements['packs'].value, 10) || 0;
var sell_price = parseFloat(this.elements['sell_price'].value) * 100 || 0;
var profit = ((sell_price - casecost) / packs) / 100;
this.elements['profit'].value = profit.toFixed(2);
Also note that if packs is 0, then you'll have a divide by zero error. You'll want to add logic to check the value of packs and do something when it's zero (not calculate the profit).