javascript numbers assignment - javascript

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

Related

How to make value auto update when input numbers are changed in javascript?

Here is a link to the tip calculator - it's hosted on netlify.
I created a tip calculator using html, scss, javascript. no tutorials used, so I'm pretty proud. It took me waaayyyyy longer than I had planned on, but it's done. needless to say, I am a complete beginner.
In any event, I need some help.
I need to know how to make the numbers auto-update if I input a new dollar amount into the billing input.
For instance, if the bill is $50, and the tip percent is 50% that's a $25 tip Amount. for a total bill of $75 dollars.
But let's say I mistyped the bill, so I go back to put in $60, 50% of $60 is $30. so the total bill amount should auto-update to $90. But I can't figure out how to get all of that to happen instantaneously when I change the dollar amount in the billing input.
I have a feeling that it has something to do with using a "change" event listener. but I don't understand how to best implement it, or if that's even the answer here.
// Upper Box Selections
const tipPercent = document.querySelector(".tip-percent");
const tipSlider = document.querySelector("#tip-slider");
tipSlider.oninput = function () {
billInput = Number(document.querySelector("#bill-amt").value);
tipPercent.innerHTML = this.value + "%";
//Discovered that number input type still returns a string
//You can wrap multiple variables in parenthesis in order to append methods
let tipAmount = document.querySelector(".tip-amount");
// if a variable is referenced but not defined, it will be added to the window element - can now use in second function
tipTotal = Number((billInput * Number(this.value / 100)).toFixed(2));
tipAmount.innerHTML = "$" + tipTotal.toFixed(2);
const billTotal = document.querySelector(".bill-total");
billForSplit = Number(billInput + tipTotal).toFixed(2);
billTotal.innerHTML =
"<strong>$</strong>" + "<strong>" + billForSplit + "</strong>";
};
// Bottom Box Selections
// -Grab slider value
const splitSlider = document.querySelector("#split-slider");
splitSlider.oninput = function () {
// -Grab split person value-split PERSON for 1, people for more than 1
const splitPeople = document.querySelector(".split-people");
if (splitSlider.value <= 1) {
splitPeople.innerHTML = splitSlider.value + " person";
} else {
splitPeople.innerHTML = splitSlider.value + " people";
}
// -grab tip per person value
const splitTip = document.querySelector(".split-tip");
// -grab total bill per person value
const splitTotal = document.querySelector(".split-total");
// - tip per person equals tipTotal / split slider value
splitTip.innerHTML = "$" + (tipTotal / splitSlider.value).toFixed(2);
// -total bill/person = billTotal / splitSlider.value
splitTotal.innerHTML =
"<strong>$</strong>" +
"<strong>" +
(billForSplit / splitSlider.value).toFixed(2) +
"</strong>";
};
https://wonderful-meninsky-e0b1c7.netlify.app/
You should declare the function with a name like calcTotal() which will be run every time there is an input for the bill and tip:
const tipPercent = document.querySelector(".tip-percent");
const tipSlider = document.querySelector("#tip-slider");
function calcTotal() {
billInput = Number(document.querySelector("#bill-amt").value);
tipPercent.innerHTML = this.value + "%";
//Discovered that number input type still returns a string
//You can wrap multiple variables in parenthesis in order to append methods
let tipAmount = document.querySelector(".tip-amount");
// if a variable is referenced but not defined, it will be added to the window element - can now use in second function
tipTotal = Number((billInput * Number(this.value / 100)).toFixed(2));
tipAmount.innerHTML = "$" + tipTotal.toFixed(2);
const billTotal = document.querySelector(".bill-total");
billForSplit = Number(billInput + tipTotal).toFixed(2);
billTotal.innerHTML =
"<strong>$</strong>" + "<strong>" + billForSplit + "</strong>";
};
tipSlider.oninput = calcTotal;
document.querySelector("#bill-amt").oninput = calcTotal;

How to store results of an iteration in a variable

For educational reasons, I am working through a simple algorithm that randomly generates two numbers and then asks for the addition of generated numbers, tells you if you are right or wrong on response, and tracks results out of 100. I would like to include function that reports something like the following: "You have gotten 80/100 correct" But am held up with syntax, I think. I can't get my score variable to count up with correct answers.
Here is my code as it stands..
do{
var firstnum = Math.floor(Math.random()*10);
var secondnum = Math.floor(Math.random()*10);
var result = firstnum+secondnum;
var score=0;
var answer = prompt("what is "+firstnum + "+" + secondnum);
if(answer < result || answer > result){alert("Wrong! " + "The correct answer
is " + result)};
if(answer == result){alert("you are correct!"), score++};
alert("Awesome, You have gotten " + score + " correct so far!!!");}
while(score<100);
Just get me over the hump. I am hopeful that I can really get my head wrapped around more concepts if I can get through this little guy.
You reset score in every loop to zero. Move the declaration and initialization to top.
Some hints:
no need for semicolons after a block statement { /* code */ },
convertion of strinn to number with unary plus +
use a single if statement with else block for the opposite of the check.
// declare all variables at top
var firstnum,
secondnum,
result,
score = 0,
answer;
do {
firstnum = Math.floor(Math.random() * 10);
secondnum = Math.floor(Math.random() * 10);
result = firstnum + secondnum;
// covert input string to number with unary plus
answer = +prompt("what is " + firstnum + "+" + secondnum);
// ^
// just check the result and omit a second if clause,
// because it is just the opposite check
// take the more easy/shorter check first
if (answer === result ) {
alert("you are correct!");
score++;
} else {
alert("Wrong! " + "The correct answer is " + result)
}
alert("Awesome, You have gotten " + score + " correct so far!!!");
} while (score < 2) // take a small number for scoring check

If statement in function issue

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.

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.

why the odd results adding floats in javascript?

I have javascript code like this:
var strikePrice = parseFloat(this.props.data.strike).toFixed(1);
var commission = parseFloat(this.props.commission / 100).toFixed(2);
var callInMoney = parseFloat(strikePrice + this.state.callPrice + commission).toFixed(2);
var putInMoney = parseFloat(strikePrice - this.state.putPrice - commission).toFixed(2);
console.log("strikePrice: " + strikePrice + " commission: " + commission);
console.log("callprice: " + this.state.callPrice + " putprice: " + this.state.putPrice);
console.log("call: " + callInMoney + " put: " + putInMoney);
and the output is this:
strikePrice: 34.0 commission: 0.08
callprice: 0 putprice: 0
call: 34.00 put: 33.92
That is wrong. The call should be 34.08 (8 cents higher) just like the put is 8 cents lower.
Why is the results not correct?
Thank you
Matt
toFixed returns a string so you're actually doing some string concatenation rather than the arithmetic you expect.
Check out what happens when you just print out your initial addition.
var strikePrice = parseFloat('34').toFixed(1);
var commission = parseFloat('0.08').toFixed(2);
console.log(strikePrice + 0 + commission);
Instead, you'll need to convert those strings to numbers first.
var strikePrice = parseFloat('34').toFixed(1);
var commission = parseFloat('0.08').toFixed(2);
strikePrice = parseFloat(strikePrice);
commission = parseFloat(commission);
console.log(strikePrice + 0 + commission);
This expression:
strikePrice + this.state.callPrice + commission
Evaluates to this value:
"34.000.08"
Because commission is a string value, which is because [toFixed()][1] takes an integer and returns a string.
You need to refactor your code so that commission is a float value, or so that you call parseFloat() again on the parameters of line 3.
I can't comment on why putInMoney works for you. For me it gave "NaN".

Categories

Resources