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);
Related
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.
I am currently trying to calculate fees that my service charges for sales (8%). The seller can input the amount they want to receive, or want's the buyer to pay (Like Steam does here: http://i.imgur.com/pLFN9px.png). I am currently using this code:
function precise_round(num, decimals) {
var t=Math.pow(10, decimals);
return (Math.round((num * t) + (decimals>0?1:0)*(Math.sign(num) * (10 / Math.pow(100, decimals)))) / t).toFixed(decimals);
}
var elem = $(this);
elem.data('oldVal', elem.val());
elem.bind("propertychange change click keyup input paste", function(event){
if (elem.data('oldVal') != elem.val()) {
elem.data('oldVal', elem.val());
if(elem.attr("id")=="seller-gets") {
var cur = elem.val();
var value = cur*1.08;
$("#buyer-pays").val(precise_round(value), 2);
} else {
var cur = elem.val();
var value = cur*0.92;
$("#seller-gets").val(precise_round(value), 2);
}
}
});
});
The Receive(Left) <--> Pay(Right) conversions are not consistent. (Putting the same number the left produced back into the right gives a different left).
Sorry if this is not clear enough, I can explain it a little better if needed.
Those are inconsistent before you are doing two different things. Say for eg. lets take 5 as the left number.
8% of 5 = .4, So Right number will be 5.4
And if you put 5.4 as the right number 8% of it is .432 not .4. So the left number will be 5.4 - .432 = 4.968 and not 5.
If you want to get back the same number then you have to multiply by 1.08 for left -> right conversion and divide by 1.08 for the vice-versa.
Hope this helps.
Firstly, can you be sure that the values that are passed to the precise_round function are what you expect?
If not, then I think from looking at your code that you need to convert the raw values to float. I have had the same problem with values being one cent wrong, and converting to float fixed it.
var value = cur*1.08;
should be:
var value = parseFloat(cur)*1.08;
and
var value = cur*0.92;
should be:
var value = parseFloat(cur)*0.92;
After that, you can use value.toFixed(2) instead of rounding. Something to try anyway.
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).
So I am working on a formula with javascript.
and this is the formula. The data for the tank variables is gathered from inputfields.
y = ((tank1 + tank2 + (tank 3 /25)) - (tank4 + tank4))/100;
alert(y);
so for tank1 = 100 tank2 = 100 and tank3 = 0 tank4 = 100 and tank5 =100
according to javascript the answer to this is 9009 while it is supposed to be 0.
for tank1 = 90 tank2 = 90 tank3 = 0 tank4 = 90 and tank5 = 90 answer = 818.6
I tried changing the divisions to multiplications /25 to 0.04 and /100 to 0.01 but the results were the same.
I also tried renaming the tanks in case they were referring to the wrong tanks.
I have also tried alerting the tanks and they gave the right inserted numbers back.
I am running Jquery.
Does anyone Know what is causing this?
Just use parseInt(tankX) for every tank variable and it will work as expected.
This is because your values come from input fields as strings not integers.
Reference: parseInt
I'm a scripting newbie who's been doing the JavaScript exercises at Codecademy for a little while now and a chance came up at work to challenge myself by building a really simple app (HTML and JavaScript)that allows someone to calculate the number of calories they can consume on a daily basis while meeting their weight loss objectives.
I've got it almost there. I had a working version (thanks to some help) that asked in the form for people to give their height in inches. The last change I wanted to make was to add the ability for them to enter their height in standard format (feet and inches) and have the app convert it in the equation. That's where the trouble started. I added a second field and renamed the variables where needed to create the conversion, but what happened is strange.
It calculates properly when something is entered into the "feet" field, but if you also add something into the "inches" field on the form, it returns results that are more than 4 times as high as they should be.
I tried moving the conversion down into the gender functions, but it made no difference. I haven't changed anything else about the code that was formerly working, so I think the issue has to be in the inches variable or in the inches form element or in the height variable where they are combined. The latter seems most likely to me, but I can't seem to find the problem.
It's probably obvious to those of you who know what you're doing so if you could take a few seconds, you'd be helping someone make the first real-world use app of their lives.
Side Note: When I open it in my browser(Chrome), the first time I fill it out, the the answer flashes and disappears. After that, each time it pulls up the answer correctly on the screen. I'm not sure if this is some mistake I've made or a browser issue or what.
<html>
<head>
<title>Daily Calorie Max</title>
</head>
<body>
<script type="text/javascript" language="javascript">
function Calculate() {
var gender = document.getElementById("gender").value;
var weight = document.getElementById("weight").value;
var inches = document.getElementById("inches").value;
var height = (document.getElementById("feet").value * 12) + inches;
var age = document.getElementById("age").value;
var goal = document.getElementById("goal").value;
if(gender=="male")
{
val1 = 6.23 * weight;
val2 = 12.7 * height;
val3 = 6.8 * age;
dailyDeficit = (goal * 3500) / 90;
result = 66 + val1 + val2 - val3;
cals = result * 1.55;
calMax = cals - dailyDeficit;
}
else if (gender=="female")
{
val1 = 6.23 * weight;
val2 = 4.7 * height;
val3 = 4.7 * age;
dailyDeficit = (goal * 3500) / 90;
result = 655 + val1 + val2 - val3;
cals = result * 1.55;
calMax = cals - dailyDeficit;
}
document.getElementById("answer").textContent = 'Your Daily Calorie Max is: ' + calMax.toFixed(0);
}
</script>
<form action="#">
Gender : <select id="gender"><option value="male">Male</option><option value="female">Female</option></select><br />
Weight : <input type="text" id="weight" />lbs.<br />
Height : <input type="text" id="feet" />ft. <input type="text" id="inches" />in.<br />
Age : <input type="text" id="age" /><br />
Goal : <select id="goal"><option value=5>Lose 5 Pounds</option><option value=10>Lose 10 Pounds</option><option value=15>Lose 15 Pounds</option><option value=20>Lose 20 Pounds</option><option value=25>Lose 25 Pounds</option></select><br />
</fieldset>
<input type="submit" value="Give me my Daily Calorie Max!" onclick="Calculate()" />
</form>
<div id="answer"></div>
</body>
</html>
The problem is here:
var inches = document.getElementById("inches").value;
var height = (document.getElementById("feet").value * 12) + inches;
You are ending up concatenating the result of the calculation for feet with the string for inches (several type coercions are occurring here - from the value of the feet element to an integer for multiplication, then from the resulting integer to a string for concatenation with the inches string).
You should use the correct types for these:
var inches = parseInt(document.getElementById("inches").value, 10);
var height = (parseInt(document.getElementById("feet").value, 10) * 12) + inches;
I also suggest using parseFloat for the float types.
This is a result of type coercion in JavaScript.
The + operator can be used to add two numbers together, but it will also concatenate strings (even if those strings contain only number values). If you try to + a string and a number, you get a string.
For example...
var resultOfAdd = 34 + 12; // resultOfAdd equals 46
var resultOfAdd = "34" + "12"; // resultOfAdd equals "3412" ("34" and "12" are strings)
var resultOfAdd = "34" + 12; // resultOfAdd equals "3412" (12 gets coerced into a string)
var resultOfAdd = parseInt("34") + 12; // resultOfAdd equals 46!
It is very important to understand the difference between a string that contains numbers (e.g. "42") and a number (e.g. 42) in JavaScript. They are two different things.
the value() you are getting is a string, you should use parseInt()
I've been playing with your code on JSFiddle but could not make it change. I've used parseInt() as necessary and changed the submit button to a regular button. One major change I want to note is I used innerHTML instead of textContent. I believe that this is the correct form for writing to <div>.
I still can't get your code to spit out an answer. Take a stab at it and see if I'm misinterpreting your code.
P.S. Please also keep your code in the <head> and not in the body.