finding value gained where am I going wrong? - javascript

I am trying to write a simple piece of script that will tell me the amount gained from the percentage difference between two values. This is what I have but it doesnt return the correct amounts.
function percentUP (money,newNum,Orignal){
var increase = newNum - Orignal;
var percent = Math.floor(Math.round(increase/Orignal*100));
var gains = Math.round((money/percent)*100);
return "you would make £" + gains + " from your " + "£" + money + " investment"
};
I have been testing it with a simple function of (10,30,10) a 200% increase, which should give me a result that reads:
"you would make £30 from your £10 investment"
but instead I get:
"you would make £5 from your £10 investment"
sorry if this is really obvious, I am just learning right now.

You made a mistake in gains calculation. Your percent is in your example equal 200. You want to multiply money by it and divide by 100.
Your calculation: money / 200 * 100 = money / 2
Expected calcualtion: money * 200 / 100 = money * 2
Corrected code:
function percentUP(money, newNum, orignal) {
var increase = newNum - orignal;
var percent = Math.round(increase / orignal);
var gains = Math.round(money * percent);
return `you would make £${gains} from your £${money} investment`
};
PS You could also remove Math.round call from percent calculation. It just messes accuracy.

Gains calculation seems wrong. It should be Original + (Original * Percent / 100). That should be 10 + (10 * 200/100). You could also use your money variable in the above example instead of Original. I wasn't sure of the difference based on what you are calculating.
Also, not sure what's the purpose of having a percentage in % form, it's simpler to just use the decimal form, ie, 2 instead of 200%. That way you avoid the conversion twice.

Related

Make Dynamic Calculations from Keyboard Input with JavaScript?

I need a simple calculation script that will take number values entered into an input field and display results dynamically based on predefined set of criteria.
For example, I have a set of fee criteria as follows:
0-150 = No charge
150-300 = Display only fixed monthly fee
300-2500 = multiply by 0.002 + fixed monthly fee - 300 = amount
enter amount more than 2500 = multiply by 0.0015 + fixed monthly fee - 300 = amount
I need the results displayed dynamically as the user is typing in the input, without pressing a button. I want to use JavaScript/jQuery for this.
How can this be done? I find it hard to set up the code. Please, help me out with directions and examples. Or better yet, guide me to the solution that will work as described. Can this be done?
I appreciate your help much and thank you all brave coders taking on this challenge! :)
Got it. So the function is as follows:
function calResult(n){
var fixedMonthlyFee = 9.95;
if(0 <= n && n <= 150){
jQuery("#desc").text("No charge");
}else if(150 <= n && n <= 300) {
jQuery("#desc").text(fixedMonthlyFee);
} else if(300 <= n && n <= 2500) {
jQuery("#desc").text(n * 0.002 * 30 + fixedMonthlyFee);
} else {
jQuery("#desc").text(n * 0.0015 * 30 + fixedMonthlyFee);
}
}
console.log('--No Erros--');
Hope that will be helpful to others!

javascript get random number: lower probability to get higher number in the interval

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];
}

Creating a Profit Calculator

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).

What's wrong with this code to find heightInInches?

After click, a calculated BMI is shown as 0.3; expected answer was 22.8
Code snippet in question:
calculateButton.addEventListener('click', function() {
var feet = feetField.value;
var inches = inchesField.value;
var heightInInches = (feet * 12) + inches;
bmiDisplay.text = ((weightField.value / (heightInInches * heightInInches)) * 703).toFixed(1);
});
heightInInches should equal 68, not 608. Seems like somehow feet (5) is being multiplied by 120 instead of 12 and then tacking on the inches (8) at the end, but I don't quite understand why that's happening, and why it's hiding from me when I step through the code?
Debugger shows the correct values for feet(5) and inches(8) in the formula but an incorrect value assigned to heightInInches after the calculation.
Link to BMI formula
I think I formatted the question correctly; long time listener, first time caller. I've just been staring at it too long... I had screenshots of my UI and the debugger but I had to remove those images from the post. Ok, thanks for checking it out.
inches is a string so when you do the + operator, it concatenates it. You can simply do
var heightInInches = (feet * 12) + inches*1;
and it will treat it as a number.
Try by adding:
var feet = parseFloat(feetField.value);
var inches = parseFloat(inchesField.value);

Javascript Calc if 1 multiple by 2 for example

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.

Categories