How to get if/else statement to work inside function - javascript

I'm trying to use an if/else statement inside a function to make it so that orders over 50 have free shipping (s = 0).
I previously had shipping equal 15% of the cost of the order, which is now commented out. The function did work before I tried to add the if/else statement.
There are no error codes showing.
function estcost() {
var p = document.getElementById("price").value; //gets price for plant as entered in box by user
var p = parseFloat(document.getElementById("price").value);
var t = 0.086 * p; //calculates arizona sales tax
//var s = 0.15*p;//calculates shipping cost based off of 15% of plant cost
var s;
if (p < 50) {
s = 0.15 * p; //shipping for orders under $50
} else {
s = 0; //shipping for orders $50 and over
}
return s;
var c = t + s + Number(p); //calculates final cost
var f = '$' + c.toFixed(2); //rounds cost to 2 decimal places
document.getElementById("result").innerHTML = f; //allows me to call f in html
}

You have a couple of issues:
You declare p twice. While this isn't completetly wrong, there is no need to do it. Remove the first var p = document....
You return s before you display your results. Using return will stop the function from running, thus making all the code below it not run. Either remove this (if your not doing anything with it) or move it to the bottom of your function.
Although it isn't a necessary change, you can instead declare var s to be var s = 0 and only change it if p < 50, allowing you to remove the else.
See working example below:
function estcost() {
var p = parseFloat(document.getElementById("price").value);
var t = 0.086 * p; //calculates arizona sales tax
var s = 0;
if (p < 50) {
s = 0.15 * p; //shipping for orders under $50
}
var c = t + s + Number(p); //calculates final cost
var f = '$' + c.toFixed(2); //rounds cost to 2 decimal places
document.getElementById("result").innerHTML = f; //allows me to call f in html
return s; // move to bottom
}
<input type="number" placeholder="price" id="price" />
<p>Result: <span id="result"></span></p>
<button onclick="estcost()">Estimate Cost</button>

The problem is your return statement is too soon in your function - it stops the rest of the function from executing. Placing the return statement at the bottom of the function should fix this problem:
function estcost() {
var p = document.getElementById("price").value; //gets price for plant as entered in box by user
var p = parseFloat(document.getElementById("price").value);
var t = 0.086 * p; //calculates arizona sales tax
//var s = 0.15*p;//calculates shipping cost based off of 15% of plant cost
var s;
if (p < 50) {
s = 0.15 * p; //shipping for orders under $50
} else {
s = 0; //shipping for orders $50 and over
}
var c = t + s + Number(p); //calculates final cost
var f = '$' + c.toFixed(2); //rounds cost to 2 decimal places
document.getElementById("result").innerHTML = f; //allows me to call f in html
return s;
}

Related

What is the statement i need next to determine my output given a total?

I'm quite new to JavaScript so apologies in advanced, but I'm wanting too learn!
In my html form I am asking the customer for 3 numbers (number 1,2,3) and then in my JavaScript I am calculating the total of all of them. I need to work out my next bit of code so I can:
Given the total of the numbers give I can print out to the customer you're item is free (less than 180) or it has a cost (more than 180)
Given the number is under or over a certain amount return an error message
Where would be the best place to go with this ?
function Calculate() {
var number1 = document.getElementById("number1").value;
var number2 = document.getElementById("number2").value;
var number3 = document.getElementById("number3").value;
// var totalOfNumbers = Number(number1) + Number(number2) + Number(number3);
document.getElementById("total").innerHTML = Number(number1) + Number(number2) + Number(number3);
}
You need to use an if construct.
The code would be :-
function Calculate() {
var number1 = document.getElementById("number1").value;
var number2 = document.getElementById("number2").value;
var number3 = document.getElementById("number3").value;
// use parseInt instead of Number()
var totalOfNumbers =
parseInt(number1) + parseInt(number2) + parseInt(number3);
// string message to be displayed
var message = "";
// enter you own values
var minAmount = 0;
var maxAmount = 1000;
// checking if total of the numbers is under or over a certain amount;
// if it is, then showing an error message.
if (totalOfNumbers < minAmount || totalOfNumbers > maxAmount) {
message = "Error! Please enter valid amounts."
}
// Checking if total of the numbers is under 180;
// if it is, then displaying the item is free.
else if (totalOfNumbers < 180) {
message = "You're item is free!";
}
// Checking if total of the numbers is greater than or equal to 180;
// if it is, then displaying the item is not free, and its cost.
else {
message = "You're item is not free. It has a cost of $" + totalOfNumbers;
}
document.getElementById("total").innerHTML = message;
}

JavaScript syntax problem - Tip Calculator

Please, could you guys explain this syntax/expression problem?
I was practicing and I tried to create a Tip Calculator which will give me a tip value according to the bill value and percentage.
I can not understand why the expression in the variable finalValues1 does not work.
JSFiddle code result. Thank you very much.
document.getElementById('myForm').addEventListener('submit', function (e) {
e.preventDefault();
var bill, tip, percentage, finalValues1, finalValues2;
bill = document.getElementById('bills').value;
if (bill < 50) { // if bill less $50, give tip of 20%.
percentage = .2;
} else if (bill > 50 && bill < 200) { // if bill greater $50 and less than $200, give tip of 15%.
percentage = .15;
} else {
percentage = .1; // if bill greater than $200, give tip of 10%.
}
tip = bill * percentage;
// I want also to display the final value bills plus tip
finalValues1 = bill + tip; // This code does not work, it is concatenating bills and tip.
finalValues2 = bill * 1 + tip; // this code works and it sums bill plus tip. WHY is that?
document.getElementById('demo').innerHTML = "Tip: " + tip + " and total bill plus tip test1: " + finalValues1 + " test2: " + finalValues2 ;
});
bills.value is a string , not a number
if you want to get a number use bills.valueAsNumber
code:
const myForm = document.getElementById('my-form')
myForm.onsubmit=e=>
{
e.preventDefault()
let bill = myForm.bills.valueAsNumber
, percentage = (bill < 50) ? 0.2 : (bill < 200) ? 0.15 : 0.1
, tip = bill * percentage
;
myForm.demo.textContent = `Tip: ${tip.toFixed(2) } ___ total (bill + tip): ${(bill + tip).toFixed(2)}`
}
<form id="my-form" >
<output name="demo">???</output>
<br>
<br>
<label for="bills">Bill Value :</label>
<input name="bills" autocomplete="off" type="number" required step="0.01">
<br>
<br>
<button type="submit">submit</button>
</form>
as you see it is more easy to use form names instead of elements ID
Use this instead finalValues1 = Math.parseFloat(bill) + Math.parseFloat(tip);
It'll force your code to treat both variables as floats (decimal numbers), rather than strings.
Here is what I would do:
function TipCalc(percent = 20){
this.percent = percent; this.tip = this.total = 0;
this.calc = bill=>{
let t = this.percent/100*bill;
this.tip = t.toFixed(2); this.total = (bill+t).toFixed(2);
return this;
}
}
const tc = new TipCalc;
function billTest(bill){
let p;
if(bill < 50){
p = 20;
}
else if(bill < 200){
p = 15;
}
else{
p = 10;
}
tc.percent = p; tc.calc(bill);
console.log({percent:p, tip:tc.tip, total:tc.total});
}
billTest(15.72); billTest(200.01); billTest(50.01);
Note that tipCalcInstance.tip and tipCalcInstance.total are Strings.
You need to parse the value as a float bill = parseFloat(document.getElementById('bills').value);
And you really should have 0's at the start of your decimals.
You also need to check your order of operations finalValues2 = bill * 1 + tip;
Since multiplication is applied first, this will always just be (bill * 1) + tip.
Change it to bill * (1 + tip)

JavaScript function "X - Y = Z" returns Y as Z value

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

How to make a function that will calculate the area under the curve of the graph using node.js?

I need to make the function so that it calculate the area when I enter function f and coefficients a, b and n on the command line.
For now I have this:
module.exports = function (f,a,b,n,next) {
parseFloat(a);
parseFloat(b);
parseInt(n);
var h = (b-a)/n;
var s = 0;
var suma = function () {
for (var i = 0; i <= n; i++) {
var ximj = a+h*(i-1);
var xi = a+h*i;
var x = (ximj + xi)/2;
s += eval(f,x);
}
return s;
};
if (n<1) {
next(new Error("Koeficijent n je broj ekvidistantnih točaka."))
}
else next(null, {povrsina : function () {return h*suma();}}
);
I think that the function suma() isn't working like it should be working.
In command line this should be look like :
f: x*x-2*x+7
a: 2
b: 4
n: 10
Povrsina ispod grafa funkcije f je 20.66000...
My prompt file looks like this:
var pov = require('./integrator.js');
var prompt = require('prompt');
prompt.get (['f','a','b','n'],function (err,koef) {
if (err) return console.log(err);
console.log("f: ",koef.f);
console.log("a: ",koef.a);
console.log("b: ",koef.b);
console.log("n: ",koef.n);
parseFloat(koef.a);
parseFloat(koef.b);
parseInt(koef.n);
pov(koef.f,koef.a,koef.b,koef.n,function(err,rj){
if (err)
console.log(err);
else
console.log("Povrsina ispod grafa funkcije f je " + rj.povrsina());
});
Thank you for help :)
First of all, if you want to calculate the area under a curve you are going to need to provide a lower and upper x limit, otherwise the answer will always be infinite. Personally I use this function that I wrote:
function findArea(lowerLimit, upperLimit, coefficients) {
let lower = 0
let upper = 0
for (let i = 0; i < coefficients.length; i++) {
lower += (coefficients[i] * Math.pow(lowerLimit, i + 1)) / (i + 1)
upper += (coefficients[i] * Math.pow(upperLimit, i + 1)) / (i + 1)
}
return Math.abs(upper - lower)
}
If you pass in two numbers as the limits and an array of coefficients in the format, a + bx + cx^2 + dx^3 ... and so on, you will get the correct answer. For example, say you have the equation y = 5 + 4x + 3x^2 + 2x^3 and you want to find the area under the curve between x = 1 and x = 3 you can call this function like so, findArea(1, 3, [5, 4, 3, 2]) and you will get the answer 92 which represents the number of units squared. Keep in mind that this works only if the area you are evaluating is either entirely above or entirely below the x axis. If your area crosses the x axis you will need to calculate the area above and below separately!
You can check the results against the Symbolab Area Under The Curve Calculator but this should work for any curve.
The eval function reads a string and evaluates it. If you want to evaluate the function f with the parameter x, then you can just write f(x) instead of calling eval(). This is because, in JavaScript, functions are first-class values and can be passed around just like numbers, strings, and so on.
In suma, particularly the line var ximj = a+h*(i-1);, your for-loop multiplies h by -1, then by 0, then by 1. I suspect you meant var ximj = a+h*(i+1); since h is the width of your differential. But that would only produce small errors.
As Lends wrote, you also need to correct your Parse* calls:
a = parseFloat(a);
b = parseFloat(b);
n = parseInt(n);
You should use math.js to eval a string math expression, for example:
var math = require('mathjs');
var integral = function(f, a, b, n, next) {
a = parseFloat(a);
b = parseFloat(b);
n = parseInt(n);
var h = (b - a) / n;
var s = 0;
var suma = function() {
for (var i = 0; i <= n; i++) {
var ximj = a + h * (i - 1);
var xi = a + h * i;
var x = (ximj + xi) / 2;
s += math.eval(f, { x: x });
}
return s;
};
if (n < 1) {
next(new Error("Koeficijent n je broj ekvidistantnih točaka."))
} else {
next(null, { povrsina: function() { return h * suma(); } });
}
};
var f = 'x * x - 2 * x + 7';
var a = '2';
var b = '4';
var n = '10000';
integral(f, a, b, n, function(err, rj) {
if (err)
console.log(err);
else
console.log("Povrsina ispod grafa funkcije f je " + rj.povrsina());
});
/* output:
Povrsina ispod grafa funkcije f je 20.66806662000201
*/
You integral function seems to have an has an issue though, n must be very high to get near the expected result (like 10000). Or is it supposed to work that way? For n = 10, it gives 22 for example.
Another solution is to use an existing package or at least read the source code to get an idea.

using if statements with input values jquery

I have a short script that calculates a number by multiplying input values. That script works fine but now I want to add if statements. For example:
HTML:
<label>Width</label><input type="text" id="width" />
<br>
<label>Length</label><input type="text" id="length" />
<br>
<label>Total</label><input type="text" id="total"/>
JavaScript:
var w = $('#width').val();
var l = $('#length').val();
var total1 = 2;
var total2 = 3;
if((w * l) > 5){
total = total1 * (w + l);
parseInt($('#total').val('total'));
}
if((w * l) < 5){
totalnew = total2 * (w + l);
parseInt($('#total').val(totalnew));
}
So if (#width x #length) > 5, the value of (#width x #length) would be multiplied by a certain number, in this case "2".
Tried to figure it out on jsfiddle.
Here is the code that works without the if statements: http://jsfiddle.net/e45SJ/
How can I implement what I am looking to achieve with the if statements with the code I already have?
EDIT: How can I add more than one if statement? I tried this: http://jsfiddle.net/m2LxV/2/
There are multiple problems
You need to do the calculation in a change handler which will get called when length/height is changed
You are doing a string concatenation when you do w + l because both w and l are string values
l + w is 5 then none of your if conditions are satisfied.
parseInt($('#total').val('total')) just assigns the value total to the element and the parseInt does not make any sense
You need to use a change handler
jQuery(function () {
var total1 = 2;
var total2 = 3;
$('#width, #length').change(function () {
var w = +$('#width').val();
var l = +$('#length').val();
var total;
if ((w * l) > 5) {
total = total1 * (w + l);
} else {
total = total2 * (w + l);
}
$('#total').val(total);
})
})
Demo: Fiddle
Since the question asked to use your code to make the modification thats what I did. Not much has changed here and I commented any parts that might seem difficult.
function calculate()
{
//Parse the string value into an integer
var w = parseInt($('#width').val());
var l = parseInt($('#length').val());
var total1 = 2;
var total2 = 3;
//Perform IF
//suggestion to use an If {} Else
if((w * l) > 5)
{
//Set an internal value of total
var total = total1 * (w + l);
//Update the label's value to total
$('#total').val(total);
}
if((w * l) < 5)
{
//Same logic as above
var total = total2 * (w + l);
$('#total').val(total);
}
}
//Simple button event for testing
$('button').click(function()
{
calculate();
});
http://jsfiddle.net/LLu5s/
Some things to keep in mind
This is a great case to use an IF ELSE logic block
$('#total').val('total') translates to > Select the input element and set its value the string string value of "total"
parseInt() will convert the string value to integer. So even though you selected the value from width and length its of type string. so performing (w + l) will actually result in combining the two strings together, not adding numbers.

Categories

Resources