This is supposed to be a simple order calculator, but for some reason it's just not working. Here's the code:
var name, product, price, discount, quantity;
var name = prompt("What is your name?", "Enter name");
var sentence = "Hello " + name + " please look through our available products and services before placing your order.";
alert(sentence);
var product = prompt("Please enter the name of the product you are looking to purchase from the table.", "Enter product");
var quantity = 1*prompt("How many " + product + " would you like to purchase?", "Enter quantity");
var cost = price * quantity;
var orderdiscount = price * discount * quantity;
var totalcost = cost - orderdiscount;
a = confirm(+ name + ", you ordered " + quantity + " of " + product + ". Is this correct?");
if (a) {
total = cost - (price * discount * quantity);
if (product === "ice cream cake") {
price = 20;
discount = .15;
} else if (product === "ice cream cone") {
price = 3;
discount = .01;
} else if (product === "small ice cream sundae") {
price = 5;
discount = .05;
} else if (product === "large ice cream sundae") {
price = 6;
discount = .05;
} else if (prompt = ("Sorry, " + name + ". You entered an invalid product. Refresh the page to reload and place the order again.")) {
}
}
else
{
alert("Refresh the page to reload and place a new order");
}
document.write("Thank you for placing an order with us, " + name + ".");
document.write("</br>");
document.write("The cost of buying " + quantity + " of " + product + " is " + cost + ".");
document.write("</br>");
document.write("The discount for this purchase is " + orderdiscount + ".");
document.write("</br>");
document.write("With the discount, your total order cost is " + totalcost + ".");
When I load the page and enter all of the necessary information, it returns:
"Thank you for placing an order with us, .
The cost of buying 1 of ice cream cake is NaN.
The discount for this purchase is NaN.
With the discount, your total order cost is NaN."
There are supposed to be calculated numbers in place of those NaNs. What in this code is causing this to happen?
You are doing your calculation before you are setting the values of your variables.
var cost = price * quantity; <-- calculation here
....
total = cost - (price * discount * quantity); <-- calculation here
if (product === "ice cream cake") {
price = 20;
discount = .15; <-- setting variable here
}
I would say it is because the value of price is not set anywhere and is left undefined by the time it is used.
Therefore when you calculate cost you are multiplying price (which is undefined) by quantity, and thus you will not get a valid result
The main problem I can see it the cost variable using the price variable before it has been assigned a value, first add simply change var cost = price * quantity; to this var cost = function(){return price*quantity;};
this way each time you call cost it will recalculate the price*quantity rather than at the top of the file before you've done the operations to get the price.
This happens because until here if (product === "ice cream cake") {
price = 20;
discount = .15;
} else if (product === "ice cream cone") {
price = 3;
discount = .01; price and discount are Null.
Use parseInt(..) on return value of :
prompt("How many " + product + " would you like to purchase?", "Enter quantity")
You're calculating cost before You set the price.
price is undefined for a kickoff, but even so, if the user was to order a dozen or twelve instead of 12 of whatever item he/she orders, you'll still end up with a NaN when quantity = 1*'a dozen';. Checking user input will always be a necessity
Is it the fact you're not declaring the price? If it's not a needed field for your user. Hide it.
Jonah
Related
I'd like to create an average calculator for test scores. Have the user enter numbers. They can enter as many as they want. Once they enter “-1”, end the program. Display the lowest test score, the highest test score, the sum of all test scores, and the average of all test scores.
The following is my code. I've already figured out how to do the sum of the scores. However, I don't know how I can turn ALL my inputs into a string - possibly output the lowest (Math.min), highest (Math.max) and average of the test score.
I tried joining strings together but in the end I couldn't figure out how to work!
while (true) {
var itemGrade = parseFloat(prompt("Enter a grade!\n\n(enter -1 to quit)"));
var item = itemGrade + ", "
total += itemGrade;
if (itemGrade == -1) {
break;
}
}
document.write("Total: " + total)
Here is a short piece of code that should do the job. The syntax ${variable} with ` allows variables to become strings. Total score is how you've written it. Lowest and highest simply checks if the new score entered is a higher or lower number and replaces the variable as the new lowest/highest. A count is added to calculate the average of all scores.
var total_score = 0.0;
var average_score = 0.0;
var lowest_score = Infinity;
var highest_score = 0.0;
var count = 0.0;
while (true) {
var itemGrade = parseFloat(prompt("Enter a grade!\n\n(enter -1 to quit)"));
if (itemGrade == -1) {
break;
}
total_score += itemGrade;
if (lowest_score > itemGrade){
lowest_score = itemGrade;
}
if (highest_score < itemGrade){
highest_score = itemGrade;
}
count++;
}
average_score = total_score/count;
document.write("Total Score: " + `${total_score}`);
document.write("Average Score: " + `${average_score}`);
document.write("Lowest Score: " + `${lowest_score}`);
document.write("Highest Score: " + `${highest_score}`);
var item = []
item.push(itemGrade)
You can create an empty array and use push() inside the while loop to add value to end of an array or use unshift() in case you want to add in starting position of the array
I have a 'calculate' button that takes the quantity entered and multiplies it by the value of an item. JS is below:
function calculate() {
var totalPrice=0;
var price = document.getElementById("itemprice").innerHTML;
var quantity = document.getElementById("quantity").value;
totalPrice=price * quantity;
document.getElementById("totalamount").innerHTML="$" + totalPrice;
//document.write(price * quantity)
}
The above works perfectly for the calculate button. I'm looking to add to this
What I want to also achieve is adding an alert pop up should the "totalprice" result equals zero, a negative number, or NaN (if someone inputs a letter into the quantity box).
So adding to the above something like this:
if ("totalPrice" < 1, NaN)
alert (Please Enter valid quantity)
But I just don't seem to be able to make it work.
totalPrice is variable, if you put it in quotes its a string
if you need 2 conditions in if use || an or operator in your case. Also read: javascript multiple OR conditions in IF statement
Read here how to check for NaN
totalPrice = "not a number"
if (isNaN(totalPrice) || totalPrice < 1) {
alert("Please Enter valid quantity")
}
So you should use:
function calculate() {
var totalPrice = 0;
var price = document.getElementById("itemprice").innerHTML;
var quantity = document.getElementById("quantity").value;
totalPrice = price * quantity;
if (isNaN(totalPrice) || totalPrice < 1) {
alert("Please Enter valid quantity")
} else {
document.getElementById("totalamount").innerHTML = "$" + totalPrice;
}
}
I am trying to make my program work, but something is wrong. I want to do a simple tax program, where I am calculating the total price including tax on X amount of items. I want to enter the values using prompt command in JavaScript. Here is my code:
let phonePrice;
let quantity;
let tax;
let total;
let total2;
phonePrice = prompt('Enter the phone price here...','');
quantity = prompt('Enter quantity here...','');
tax = phonePrice * 0.05;
total = phonePrice + tax;
total2 = quantity * total
alert('The Price on ' + quantity + ' phones with tax included is ' + total2 + ' dollars.');
Everything works fine until I want to add decimal number as value. Quantity can't be decimal number of course, but, for example, the item price can be 119.95 dollars. When I enter this number directly in ti the script (without prompt) everything is fine, but when i declare prompt and enter the same value in the browser, it give me NaN as value which is not a number. Anyone got any explanation, and how can I fix this?
Try to debug your code, and you will see that problem not in parsing :)
You have STRING in phonePrice (the result of promt is string, let it be '10.5')
Then you have (tax = phonePrice * 0.05;) Result will be float (autoconverted) = 0.525
Then you have (total = phonePrice + tax;) Result will be STRING = "10.50.525" - because in '+' operator , if any argument STRING - all will be used as STRINGs
And then you got NaN in last '*' - because no one know the number "10.50.525" :) and result of float * NaN = NaN
Just try to convert input values.
let phonePrice;
let quantity;
let tax;
let total;
let total2;
phonePrice = parseFloat(prompt('Enter the phone price here...',''));
quantity = parseFloat(prompt('Enter quantity here...',''));
tax = phonePrice * 0.05;
total = phonePrice + tax;
total2 = (quantity * total).toFixed(2); // Needed for correct result to money conversion
alert('The Price on ' + quantity + ' phones with tax included is ' + total2 + ' dollars.');
You have to convert the input from the prompt, which is parsed as a string, into a number, with parseFloat and parseInt:
let phonePrice;
let quantity;
let tax;
let total;
let total2;
phonePrice = parseFloat(prompt('Enter the phone price here...',''));
quantity = parseInt(prompt('Enter quantity here...',''));
tax = phonePrice * 0.05;
total = phonePrice + tax;
total2 = quantity * total
alert('The Price on ' + quantity + ' phones with tax included is ' + total2 + ' dollars.');
That said, you should instead count your money in cents instead of dollars, and use integers instead of floats, to avoid errors with floating-point accuracy.
This is my first time asking a question here, so I hope I'll do it correctly.
Just to give context, I'm developing a small website where lawyers can buy a digital version of some legal documents, but I'm having trouble calculating tax on the total cost.
The taxes are calculated with two rates used in the province of Quebec, Canada: GST (5%) and QST (9.975%). Both rates are calculated using the subtotal amount. Here's what I tried so far:
$("#formchoix #checkall").click(function () {
var tps = 0.05; //5%
var tvq = 0.09975; //9.975%
var subtotal = 0;
var total = 0;
if ($("#formchoix #checkall").is(':checked')) {
$("#formchoix input[type=checkbox].checkchoix").each(function () {
//check all forms
$(this).prop("checked", true);
$(".checknom").prop("checked", true);
$(".checkid").prop("checked", true);
subtotal += 15; //each form is 15$
$('#subtotal').html(subtotal + '.00$'); //subtotal shown to user
var taxes = subtotal * tps * tvq;
total = subtotal + taxes;
$('#totalcost').html(total.toFixed(2) + '$'); //total shown to user
$('#inputTotal').val(total.toFixed(2)); //value to be sent to server
});
} else {
$("#formchoix input[type=checkbox]").each(function () {
//reset everything: checkboxes, value and total shown to user
$(this).prop("checked", false);
$(".checknom").prop("checked", false);
$(".checkid").prop("checked", false);
subtotal = 0;
total = 0;
$('#subtotal').html('0.00$');
$('#totalcost').html('0.00$');
$('#inputTotal').val('0.00');
});
}
});
The above code doesn't give me the right number though. For example, if my subtotal is 30$, it will show 30.15$ instead of 30.49$ like it's supposed to (based on a tax calculator online).
I've also tried using values like 1.05 and 1.09975 and multiplicating them to the subtotal directly using total = subtotal * tps * tvq, but the total gave me 30.64$ (if the subtotal is 30$ like my previous example)
Clearly what I did is wrong, so how can I make sure the total is right?
30 * 0.05 * 0.09975 = 0.149625, which is rounded to 0.15 by calling toFixed(2). Math doesn't lie. As others suggested, you're taxing taxes.
var taxes = subtotal * tps * tvq;
total = subtotal + taxes;
should be changed to
total = subtotal + subtotal * tps + subtotal * tvq;
or
total = subtotal * (1 + tps + tvq);
I am having trouble with a simple JavaScript calculation. My document is supposed to add $1.50 to an order if it is $25 or less, or add 10% of the order if it is more then $25. The exact problem is:
Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box.
This is my code:
var price = window.prompt("What is the purchase price?", 0);
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
When testing I enter a number in the prompt box, and instead of calculating as if I entered a number it calculates as if I entered a string. i.e. i enter 19 and it gives me 191.5 or I enter 26 and it gives me 262.6
Using parseFloat will help you:
var price = parseFloat(window.prompt("What is the purchase price?", 0))
var shipping = parseFloat(calculateShipping(price));
var total = price +shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
See it working at: http://jsfiddle.net/e8U6W/
Also, a little-known put more performant way of doing this would be simply to -0:
var price =window.prompt("What is the purchase price?", 0) - 0;
(See: Is Subtracting Zero some sort of JavaScript performance trick?)
Be sure to comment this, though as its not as obvious to those reading your code as parseFloat
you can easily convert a string to a number
http://www.javascripter.net/faq/convert2.htm
basically JS provides parseInt and parseFloat methods...
Actually, you need to cast your text results into float values using parseFloat()
http://www.w3schools.com/jsref/jsref_parseFloat.asp
See my answer to the s/o question "Javascript adding two numbers incorrectly".
A bit of redundant multiplication, but your problem is that the numbers that are being inputted are treated as strings, not numbers. You have to convert them to floating point numbers:
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price)
{
if (price <= 25)
{
return 1.5;
} else {
return price / 10
}
}
window.alert("Your total is $" + total + ".");
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
var num = new Number(price);
if (num <= 25){
return 1.5;
} else{
return num * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
This should do it for you.