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.
Related
I'm building an app that tracks stock predictions.
I would like to have a function that takes in two numbers, and calculate the return on investment between the two numbers.
For example with a start price of $50, and a current price of $100, the function should return "100", since the price has increased 100% since the first purchase. With a start price of $100, and a current price of $10, the function should return "-90", since that investment would have lost 90% of its value
This seems more like a math question than a programming question, but here goes:
function roi(cost, profit) {
return (profit - cost) / cost * 100;
}
function getROI(cost, profit) {
return (profit - cost) / cost;
}
let startPrice = 50
let endPrice = 100
let ROI = 100 * ((endPrice/startPrice) - 1)
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);
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
I need to write a piece of code that requests a value for the number of years of a contract. Then use a for loop to calculate a discount factor of 2% per year, i.e. if it is a one year contract, the price will be 98% of the full price, if it is a two year contract, the price will be 96% of the full price, and so on.
I seem to be a little stuck and not sure if I have totally grasped what they are asking.
Here is what I have already done:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transition//EN" "http://www.w3.org/TR/xhtml/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type = "text/javascript">
var stringVariable = prompt ("Enter the number of people")
var numberVariable
var loopCounter = prompt ("How many years?");
var numberCount = new Array(100/2);
if (stringVariable <= 30) {
numberVariable = 15*stringVariable;
}
else if (stringVariable> 30 && stringVariable<60) {
numberVariable = 12*stringVariable;
}
else if (stringVariable>60) {
numberVariable =12*stringVariable;
}
alert ("Total cost is: $" + numberVariable);
for (loopCounter = 0; loopCounter <= 4; loopCounter++)
{
document.write("Total discount $" + loopCounter - numberCount[loopCounter] + "<br />");
}
alert ("Total cost is: $" + numberVariable - numberCount);
</script>
</body>
</html>
Thanks in advance for any help.
Your code seems to be fundamentally flawed in a few places, especially your variable names.
Here's how I'd tackle the problem:
// parseInt() converts strings into numbers. 10 is the radix.
var num_people = parseInt(prompt('Enter the number of people'), 10);
var num_years = parseInt(prompt('How many years?'), 10);
// Initialize your variables.
var cost = 0;
var discount = 1.00;
// Your if condition was a bit odd. The second part of it would be
// executed no matter what, so instead of using else if, use an
// else block
if (num_people <= 30) {
cost = 15 * num_people;
} else {
cost = 12 * num_people;
}
alert('Total cost is: $' + cost);
// Here is a for loop. i, j, k, ... are usually
// used as the counter variables
for (var i = 0; i < num_years; i++) {
// Multiplying by 0.98 takes 2% off of the total each time.
discount *= 1.00 - 0.02;
// You fill the rest of this stuff in
document.write('Total discount $' + ... + '<br />');
}
// And this stuff
alert('Total cost is: $' + ...);
How do I get cart checkout price exact to the penny using Javascript?
Right now after taking out all of the trial .rounds etc I was trying.. I am coming up 1.5 cents too high using a high 15 products/prices to test.
for (var i = 0; i < Cookie.products.length; i++) {
boolActive = Cookie.products[i].og_active;
if (boolActive)
{
itemPrice = Cookie.products[i].price;
itemQty = Cookie.products[i].quantity;
itemDiscountPercent = Cookie.products[i].discount_percent;
subtotal = itemPrice * itemQty;
priceDiscount = (subtotal * itemDiscountPercent);
discountAmount += priceDiscount;
}
}
if (!isNaN(discountAmount))
{
var newCartTotal = (cartTotal - priceDiscount);
alert("New Cart Total: " + newCartTotal);
}
var newCartTotal = (cartTotal - pricediscount).toFixed(2)
that will give you the value, but it will be a string. If you need it to stay numeric, use:
var newCartTotal = ((cartTotal - pricediscount * 100) << 0) / 100;
You need to round the discount for each line item: priceDiscount = round_to_hundredth(subtotal * itemDiscountPercent)
Note that this result may not agree with the result you'd get if you add the unrounded results and then round the sum. However, this is the way invoices usually work when calculated by hand (especially since each item can have a different discount percent, so the discount is calculated for each line).
I think you left out a line saying discountAmount += priceDiscount.
modify your code to :
priceDiscount = parseFloat( (subtotal * itemDiscountPercent).toFixed(2) );
and:
newCartTotal = parseFloat( (cartTotal - priceDiscount).toFixed(2) );