Calculating Sales Tax Task Javascript - javascript

I'm asked to the following tasks but am having difficulty returning values.
Here's the code:
function calculateTaxes(price, quantity) {
var salesTax = .10;
var totalPrice;
return totalPrice;
}
// Test Your Code Here
calculateTaxes(1,10);
calculateTaxes(1,10) should return a number
calculateTaxes(2,5) should return a value of 11
calculateTaxes(5,6) should return a value of 33
calculateTaxes(10,3) should return a value of 33
calculateTaxes(15,12) should return a value of 198
calculateTaxes(25,2) should return a value of 55

It's quite straightforward. price*quantity gives you the total price without tax, and multiplying that with 1 + salesTax gives you the price after tax.
function calculateTaxes(price, quantity) {
var salesTax = .10;
var totalPrice = (price * quantity) * (1 + salesTax);
return totalPrice;
}
console.log(calculateTaxes(1,10));
console.log(calculateTaxes(25,2));
Don't be surprised if you see 55.00000001 instead of 55 though. Do read: Is floating point math broken?

Related

Get return on investment (ROI) from two numbers in Javascript?

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)

How to Calculate Bill Total JS

I need to write a function called "calculateBillTotal".
Given the pre tax and pre tip amount of a meal, "calculateBillTotal" returns the total amount due after tax and tip.
Notes:
* Assume that sales tax is 9.5% and tip is 15%.
* Do NOT tip on the sales tax, only on the pre tip amount.
Here's my code:
function calculateBillTotal(preTaxAndTipAmount) {
preTaxAndTipAmount - 9.5 + 15;
return preTaxAndTipAmount;
}
var output = calculateBillTotal(20);
console.log(output); // --> it must be 24.9 but its return 20 instead.
You need to figure out the math. Also, introducing temporary helper variables increases readability.
Assume that sales tax is 9.5% and tip is 15%.
9.5% of the preTaxAndTipAmount is preTaxAndTipAmount * 9.5 / 100 or simply preTaxAndTipAmount * 0.095.
15% of the preTaxAndTipAmount is then preTaxAndTipAmount * 0.150.
function calculateBillTotal(preTaxAndTipAmount) {
var tax = preTaxAndTipAmount * 0.095;
var tip = preTaxAndTipAmount * 0.150;
return preTaxAndTipAmount + tax + tip;
}
console.log(calculateBillTotal(20)); // 24.9
Come on! You are returning the same variable.
function calculateBillTotal(preTaxAndTipAmount) {
var total = preTaxAndTipAmount - 9.5 + 15;
return total;
}
And the result is 25.5, not 24.9.

JavaScript / jquery Calculations issue

Hi i have issue with the below JavaScript code not taking current GrossTotal() value until i rewrite Quantity or the UnitPrice values
$(document).ready(function () {
$("[id*=gridpur]input[type=text][id*=txtCalc]").on('keyup', (function (e) {
var unitprice = $(this).closest('tr').find("input[type=text][id*=txtCalcUnitprice]").val();
var quantity = $(e.target).closest('tr').find("input[type=text][id*=txtCalcQuantity]").val();
var total = unitprice * quantity;
var cost = (total / GrossTotal())*100;
$(e.target).closest('tr').find("[id*=lblTotal]").text(total);
$(e.target).closest('tr').find("[id*=lblcost]").text(cost);
}));
});
var gross;
function GrossTotal() {
gross = 0;
$("[id*=gridpur][id*=lblTotal]").each(function (index, item) {
gross = gross + parseInt($(item).text());
});
$("[id*=lblGrandTotal]").text(gross);
return gross;
}
for example if have entered the following values output i get which is not correct
ProductName UnitPrice Quantity Amount Cost %
product1 9 1 9 Infinity
product2 9 1 9 100
product3 9 1 9 50
I only get the correct values after rewriting Quantity or the UnitPrice which is
ProductName UnitPrice Quantity Amount Cost %
product1 9 1 9 33.3
product2 9 1 9 33.3
product3 9 1 9 33.3
Make sure, you default them to 0 when you read the value from the input. Also Check for 0 before dividing it
unitprice = !isNaN(unitprice) ? 0 : unitprice;
quantity = !isNaN(quantity) ? 0 : quantity;
var total = unitprice * quantity;
var grossTotal = GrossTotal(),
cost = 0;
if(grossTotal > 0) {
cost = (total / grossTotal) *100;
}
Also it is a better habit to use radix when using parseInt
parseInt($(item).text(), 10)
The problem is that GrossTotal() adds up the values in all the lblTotal fields, but you're not filling them in until after you call it. Change these lines:
var cost = (total / GrossTotal())*100;
$(e.target).closest('tr').find("[id*=lblTotal]").text(total);
$(e.target).closest('tr').find("[id*=lblcost]").text(cost);
to:
$(e.target).closest('tr').find("[id*=lblTotal]").text(total);
var cost = (total / GrossTotal())*100;
$(e.target).closest('tr').find("[id*=lblcost]").text(cost);

Javascript: Can't get variable sum to work with addition operator

I can't get the var total to resolve by using addition. It will work with multiplication operator:
var total = subtotal * sales_tax
but not with the + sign addition operator: var total = subtotal + sales_tax. Any help would be most appreciated.
var calculate_click = function () {
var subtotal = parseFloat(document.getElementById("subtotal").value).toFixed(3);
var taxRate = parseFloat(document.getElementById("tax_rate").value).toFixed(3);
if (isNaN(subtotal) || isNaN(taxRate)) {
}
else {
var sales_tax = (subtotal * taxRate / 100);
parseFloat(document.getElementById("sales_tax").value = sales_tax.toFixed(3));
var total = subtotal + sales_tax;
parseFloat(document.getElementById("total").value = total.toFixed(3));
}
}
toFixed() formats the number into a string. So arithmetic operations afterwards will not work as expected.
Note:
+ (concatenation) is a valid operation for strings as well, so it'll return "string1string2" - For all other arithmetic operations it auto converts the strings to numbers and performs the operation. If the data within the strings cannot be converted, it returns NaN.
"12" + "2" => "122" whereas "12" * "2" => 24 (number) and "hello" * "3" => NaN

In JavaScript doing a simple shipping and handling calculation

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.

Categories