If statement in function issue - javascript

I can't get the if/else statement in the totalBalance function to work correctly in this code and I'm not sure why.
I have tried switching the greater than to less than and seeing if it solves the outcome but it makes no difference.
jsfiddle link
var moneyAmount = 0;
var food = 0;
var bills = 0;
var total = 0;
moneyAmount = prompt("how much money do you earn per month?");
amountCheck();
document.write("Your balance is " + "£" + moneyAmount + "<br>");
food = confirm("Do you have any food bills?");
if (food === true) {
food = prompt("How much per week?")
document.write("You spend £" + food + " on food per week <br>");
} else {
alert("Lucky!")
};
totalBalance();
/* total = moneyAmount - food; */
console.log("money amount = " + moneyAmount);
console.log("food = " + food);
console.log("total = " + total);
function totalBalance() {
total = moneyAmount - food;
console.log("total is " + total);
if (total > moneyAmount) {
document.write("Your total amount of money per month is £" + total);
console.log("nay");
} else {
document.write("You need to save more money £" + total);
console.log("yay");
};
}
function amountCheck() {
while (isNaN(moneyAmount)) {
alert("Please enter a numeric value");
moneyAmount = prompt("how much money do you have to spend?");
}
}

total will never be more than moneyAmount, because total is moneyAmount - food. So if (total > moneyAmount) will never evaluate as true unless food is a negative value. Not sure what exactly you're going for, but simply changing the if statement to if (total > 0) makes more sense to me given the context.

Related

javascript numbers assignment

i'm having some issues with the final two console.logs of my script. i'm supposed to have numbers output for both but i'm getting NAN
alert("Let's make a shopping list!");
let first = prompt("What is the first item?");
let firstCost = Number(prompt("What is the cost of " + first + "?"));
let firstAmount = Number(prompt("How many of " + first + " would you like?"));
let second = prompt("What is the second item?");
let secondCost = Number(prompt("What is the cost of " + second + "?"));
let secondAmount = Number(prompt("How many of " + second + " would you like?"));
let tax = parseInt(prompt("What is the sales tax for your state?"));
let firstTotal = parseFloat(firstCost * firstAmount);
let secondTotal = parseFloat(firstCost * firstAmount);
let subTotal = parseFloat(firstTotal + secondTotal);
let taxTotal = parseFloat(subTotal * tax);
let grandTotal = parseFloat(subTotal + taxTotal);
console.log(first + " " + firstCost + " " + firstAmount + " " +
firstTotal);
console.log(second + " " + secondCost + " " + secondAmount + " " +
secondTotal);
console.log("tax: " + taxTotal);
console.log("TOTAL: " + grandTotal);
I changed all of the Number() to parseFloat() but I'm not getting the outcome I'm looking for.
Error 1. Copy/paste
This line of code is a mistake:
let secondTotal = parseFloat(firstCost * firstAmount);
You have copied-and-pasted, without changing "first" to "second".
Error 2. You haven't decided whether tax is a percentage or a decimal fraction
You are collecting an INTEGER, i.e. 5% tax will be stored as 5.
But you are using it as though it is a fraction (e.g. 5% represented as 0.05), by just multiplying it by subtotal.
Error 3. When entering data you are using 'cancel' to skip the tax value
This causes it to store NaN in the tax, and that messes up all output that depends on the tax.
Tip. To get answers quickly, get rid of all the code that is irrelevant, and make it runnable within Stack Overflow, using the "<>" icon.
That helps people help you.
let firstCost = Number(prompt("What is the cost of first ?"));
let firstAmount = Number(prompt("How many of first would you like?"));
let secondCost = Number(prompt("What is the cost of second?"));
let secondAmount = Number(prompt("How many of second would you like?"));
// In this next line you are storing an integer (e.g. 5, for 5 percent)
let tax = parseInt(prompt("What is the sales tax for your state?"));
let firstTotal = parseFloat(firstCost * firstAmount);
// This next line is a mistake
// let secondTotal = parseFloat(firstCost * firstAmount);
// You meant this:
let secondTotal = parseFloat(secondCost * secondAmount);
let subTotal = parseFloat(firstTotal + secondTotal);
// But in this line you are treating it as though it is a decimal, e.g. 0.05 for 5 percent.
// let taxTotal = parseFloat(subTotal * tax);
// You probably meant this:
let taxTotal = parseFloat(subTotal * tax/100);
let grandTotal = parseFloat(subTotal + taxTotal);
console.log("tax: " + taxTotal);
console.log("TOTAL: " + grandTotal);

Application that calculates price depending on quantity in JavaScript

I have this exercise that I am struggling to comprehend the logic to achieve the outcome when qty is more than 3:
An application to calculate the price of pizzas (listed below) that will be purchased during a promotional period. The number of pizzas will be entered by the user.
One large pizza will cost $6.45.
Two large pizzas will cost $12.00.
Three large pizzas will cost $14.00.
Four or more pizzas will use a combination of the above prices to ensure the best price for the customer. For example, the best price for five pizzas would be two pizzas ($12.00) + three pizzas ($14.00).
The algorithm must also take account of all possible situations by using sequence, selection and iteration structures.
Below is my code so far:
let calcOrder = () => {
// get inputs
var qty = document.getElementById("quantity").value;
var price = 6.45;
var price2 = 12.0;
var price3 = 14.0;
var totalPrice;
// validate missing, non-digit, negative inputs
if (qty == "") {
document.getElementById("message").innerHTML = "Missing input";
} else if (isNaN(qty)) {
document.getElementById("message").innerHTML = "Numbers only";
} else if (qty < 0) {
document.getElementById("message").innerHTML =
"Negative numbers are not allowed";
} else {
//calc total
if (qty == 1)
{
totalPrice = price;
}
else if (qty == 2)
{
totalPrice = price2;
}
else if (qty == 3)
{
totalPrice = price3;
}
//output total
document.getElementById("message").innerHTML =
`Total price is $${totalPrice}`;
}
// prevent form from submission
return false;
};
Thank you
you can use division and mod operation to calculate the price:
(this example assuming all check you did valid input are already done)
const qte = document.getElementById("quantity").value;
const price = 6.45;
const price2 = 12.0;
const price3 = 14.0;
let totalPrice;
const total3 = parseInt("" + qte / 3 + "", 10) * price3;
const total2 = parseInt("" + (qte % 3) / 2 + "", 10) * price2;
const total1 = parseInt("" + ((qte % 3) % 2) + "", 10) * price;
totalPrice = total1 + total2 + total3;
document.getElementById("message").innerHTML =
`Total price is $${totalPrice}`;
what is actually happening in the code
well it is basic mathematics, if you want to know how many 3s in your number you divide by 3 and take the integer part or floor of the result, basic division. for example 10 = 3*3 + 1 so you have 3 as a result of that division.
since you only want to apply the price of 3 pizza as top priority you do this division then multiply by the price for 3.
then come the priority for the price of 2 pizzas, but you not interested for the total number of pizzas, only what was left after you payed with the price of 3 pizzas so you do the mod operator (%) with 3 to get was left unpaid, for example 8 = 3*2 + 2, this give us 2 pizzas left unpaid so you apply the price of 2 pizzas.
the you check if a single pizza is left after you paid for 2 pizzas (which would only happen if only a single pizza was left after you paid for 3). if there is single pizza you pay for it otherwise you add nothing.
ps: after paying for pizzas in multiple of three, you only add the price of 2 pizzas or a single one, but never both, otherwise price of 3 pizzas would apply instead.
hope the explanation is clear, if not leave a comment and i'll try to adjust what was not clear.

user input - Javascript

I have a code that I am working on , it is for ordering pizza. I have been coding for 7 days and I want to find out how can I make the pizza prices bigger by the size of the pizza
For example , small pizza is 15.75$ medium is 16.75 and big is 17.75
Each time I run the code , the output is 15.75
(Look at the bottom portion)
employee = confirm("Are you ready to take an order?");
if (employee === true) {
console.log("Here is the order");
} else {
console.log("Ask another employee to take the order. If there is no one, then please take the order ");
}
let orderCount = 0;
const takeOrder = (topping, crustType) => {
orderCount++;
console.log("Order: " + crustType + " pizza topped with " + topping);
};
//
// Order comes here like this - takeOrder('pepperoni', //'texas style');
takeOrder('pepperoni', 'texas style');
//
const getSubTotal = (itemCount) => {
return itemCount * 14.5;
};
//const ^^
console.log("The Sub-Total is " + getSubTotal(orderCount) + "$");
const getTax = (itemCount) => {
return itemCount * 1.25;
};
console.log("The tax is " + getTax(orderCount) + "$");
const getTotal = () => {
return getSubTotal(orderCount) + getTax(orderCount);
};
console.log("And the final total is " + getTotal() + "$");
console.log("Thank you for taking this order.")
As for one of the comments, the price relative to size is not in your logic:
let priceBySize = {
'S': 15.75,
'M': 16.75,
'L': 14.5,
}
// size of order required - might consider also to pass quantity
takeOrder('pepperoni', 'texas style', 'M');
takeOrder('margherita', 'clasic style', 'L');
const getSubTotal = (itemCount, size) => {
return itemCount * priceBySize[size];
};
Also instead of fixed prices for size maybe you'll prefer to have multipliers for sizes and base price per type of pizza.

What code do I need, to get the pizzas ordered from my array to reappear in a different function?

What code do I need to put in, so that it will show what pizzas have been ordered. Like in the array.
Down in the calculation function I have already got the customers name and number (and address) to show up as a receipt sort of thing. But I also need it to show what pizzas have been ordered.
So I need the variable "fullorder" to show up again in the alert in the "calculation function" If that makes any sense.
Sorry if this doesn't make a lot of sense. It is tuff trying to explain it.
totalNumber = 0; // for total number of Pizzas ordered
pizzaPrice = 9.50; // price of each pizza
pizzaPriceGourmet = 15.50; //price for gourmet pizzas
orderTotalPrice = 0; // total cost of order
pizzaDeliveryPrice = 5; // price for pizza delivery
var customerName = prompt("Please enter your name.") //prompt to get the customers name
var customerNumber = prompt("Please enter your phone number.") //prompt to get the customers number
function order()
{
var pizza = new Array()
pizza[0] = document.form.hawaiian.value //allocates type of pizza in array
pizza[0] = Number(pizza[0]) //converts to number value
pizza[1] = document.form.cheese.value //allocates type of pizza in array
pizza[1] = Number(pizza[1]) //converts to number value
pizza[2] = document.form.veggie.value //allocates type of pizza in array
pizza[2] = Number(pizza[2]) //converts to number value
pizza[3] = document.form.supreme.value //allocates type of pizza in array
pizza[3] = Number(pizza[3]) //converts to number value
pizza[4] = document.form.pepperoni.value //allocates type of pizza in array
pizza[4] = Number(pizza[4]) //converts to number value
pizza[5] = document.form.meatlovers.value //allocates type of pizza in array
pizza[5] = Number(pizza[5]) //converts to number value
pizza[6] = document.form.chicken.value //allocates type of pizza in array
pizza[6] = Number(pizza[6]) //converts to number value
pizza[7] = document.form.prawn.value //allocates type of pizza in array
pizza[7] = Number(pizza[7]) //converts to number value
totalPlain = pizza[0] + pizza[1] + pizza[2] + pizza[3] + pizza[4];
totalGourmet = pizza[5] + pizza[6] + pizza[7];
var totalNumber = totalGourmet + totalPlain
var fullOrder = alert("You have ordered: " + "\n" +
"Hawaiian Pizza: " + pizza [0] + "\n" +
"Cheese Pizza: " + pizza [1] + "\n" +
"Veggie Pizza: " + pizza [2] + "\n" +
"Supreme Pizza: " + pizza [3] + "\n" +
"Pepperoni Pizza: " + pizza [4] + "\n" +
"Meat-Lovers Pizza: " + pizza [5] + "\n" +
"Chicken Pizza: " + pizza [6] + "\n" +
"Prawn Pizza: " + pizza [7]);
if (totalNumber >12) { // Limit for total amount of Pizzas ordered
alert("There is a limit of 12 pizzas per order. - PRESS 'Prevent this page from creating additional dialogs' THEN PRESS 'cancel order' AND THEN RE-ORDER! - Current total is: " +totalNumber);
} else
alert("Total number of pizzas ordered: " + totalNumber); //Total amount of pizzas ordered
calculate() //Begins calculation function
}
function calculate() //Function for the cost of the order
{
orderTotalPrice = (totalPlain*pizzaPrice + totalGourmet*pizzaPriceGourmet); //order total+ amount of pizzas ordered * pizza price
var pizzaDelivery = prompt('Would you like your order to be delivered for $5, or for pick up? -Type in "1" for delivery, and "0" for pickup.') //asks if you want your order to be delivered or not
orderTotalPrice = (orderTotalPrice + (pizzaDelivery*pizzaDeliveryPrice)); // calculates the total cost with or without the delivery cost
alert("Total cost of pizzas is: $" + orderTotalPrice.toFixed(2) ); //Display order cost as "$"0.00
if (pizzaDelivery == '1'){
var response = prompt("Please enter your address: ")
alert("The pizza should be delivered within the next 25 minutes, to this address: " +response)
alert("Thank you for ordering with Pete's Pizzas " +customerName)
alert("If anything happens to go wrong we will contact you on your number: " +customerNumber)
alert("Your order details are: " +customerName +"\n" +customerNumber +"\n" +response)
alert("To exit, just click 'ok' and then close down the program!")
} else if (pizzaDelivery == '0'){
alert("Your order will be ready for pickup in 15 minutes!")
alert("Thank you for ordering with Pete's Pizzas " +customerName)
alert("If anything happens to go wrong we will contact you on your number: " +customerNumber)
alert("Your order details are: " +customerName +"\n" +customerNumber)
alert("To exit, just click 'ok' and then close down the program!")
}
}
first you need to call order function after variable declaration:
totalNumber = 0; // for total number of Pizzas ordered
pizzaPrice = 9.50; // price of each pizza
pizzaPriceGourmet = 15.50; //price for gourmet pizzas
orderTotalPrice = 0; // total cost of order
pizzaDeliveryPrice = 5; // price for pizza delivery
var customerName = prompt("Please enter your name.") //prompt to get the customers name
var customerNumber = prompt("Please enter your phone number.") //prompt to get the customers number
order();//call order
make your calculate to this:
calculate(totalGourmet,totalPlain);// while calling
function order(){
//rest of code
if (totalNumber >12) { // Limit for total amount of Pizzas ordered
alert("There is a limit of 12 pizzas per order. - PRESS 'Prevent this page from creating additional dialogs' THEN PRESS 'cancel order' AND THEN RE-ORDER! - Current total is: " +totalNumber);
} else
alert("Total number of pizzas ordered: " + totalNumber); //Total amount of pizzas ordered
calculate(totalGourmet,totalPlain); //Begins calculation function
}
function calculate(totalGourmet,totalPlain) //Function for the cost of the order
{
//current code
}

Javascript While Loop Returning Strange Results

I apologize in advance if there are several things wrong with my code; I'm still very new to this.
I made a simple little RNG betting game, which follows:
var funds = 100;
var betting = true;
function roll_dice() {
var player = Math.floor(Math.random() * 100);
var com = Math.floor(Math.random() * 100);
var bet = prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign.");
if (player === com) {
alert("tie.");
}
else if (bet > funds) {
alert("You don't have that much money. Please try again");
roll_dice();
}
else if (player > com) {
funds += bet;
alert("Your roll wins by " + (player - com) + " points. You get $" + bet + " and have a total of $" + funds + ".");
}
else {
funds -= bet;
alert("Computer's roll wins by " + (com - player) + " points. You lose $" + bet + " and have a total of $" + funds + ".");
}
}
while (betting) {
var play = prompt("Do you wish to bet? Yes or no?");
if (funds <= 0) {
alert("You have run out of money.");
betting = false;
}
else if (play === "yes") {
roll_dice();
}
else {
alert("Game over.");
betting = false;
}
}
The code deals with losing (i.e. subtraction) just fine, but can't seem to handle the addition part. If you bet, say, 50 and win, you'll wind up with 10050. Aside from never seeking out a job as a gambling software programmer, what should I do?
prompt returns a string. Adding a number to a string results in a string:
> "12" + 13
"1213"
While subtraction results in an integer, as only string concatenation is done with a plus sign:
> "12" - 13
-1
You need to convert your user's input into an integer:
var bet = parseInt(prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign."), 10);

Categories

Resources