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.
Related
I am get a formula to calculate the Net Present Value using Rent, Number of periods, Discount Rate and Future Value.I am able to get the Present Value however, I need a formula to calculate the Net Present Value on today's date or any date a user inputs. My code is as below:
function PV() {
var future = 5000;
var type = 1;
periods = 12;
rate = document.getElementById("rate").value;
var ratePercent = periods * 100;
rate = Math.pow(1 + rate / 100, 1 / 365) - 1;
rate = eval(rate);
periods = eval(periods);
// Return present value
if (rate === 0) {
document.getElementById("presentResultValue").value = -payment * periods - future;
} else {
document.getElementById("presentResultValue").value = (
(((1 - Math.pow(1 + rate, periods)) / rate) * payment * (1 + rate * type) - future) /
Math.pow(1 + rate, periods)
).toFixed(2);
}
}
I am also using Excel to calculate this but need a way to convert it to Javascript. I am also attaching my work with excel. ExcelNPV I am still learning JavaScript so any help will be greatly appreciated. Thank you.
Came across NPV formula on my project and had to create a function for it. Finance.js is great but I didn't want to clutter my code with it because my problem was just getting this formula.
ES5 Function
/**
* Calculates the Net Present Value of a given initial investment
* cost and an array of cash flow values with the specified discount rate.
*
* #param {number} rate - The discount rate percentage
* #param {number} initialCost - The initial investment
* #param {array} cashFlows - An array of future payment amounts
* #return {number} The calculated Net Present Value
*/
function getNPV(rate, initialCost, cashFlows) {
var npv = initialCost;
for (var i = 0; i < cashFlows.length; i++) {
npv += cashFlows[i] / Math.pow(rate / 100 + 1, i + 1);
}
return npv;
}
Using the function:
var rate = 10;
var initialCost = -25000;
var cashFlows = [-10000, 0, 10000, 30000, 100000];
console.log(getNPV(rate, initialCost, cashFlows));
// expected output: 56004.77488497429
JavaScript ES6 Function:
https://www.evermade.fi/net-present-value-npv-formula-for-javascript/
/**
* Calculates the Net Present Value of a given initial investment
* cost and an array of cash flow values with the specified discount rate.
* #param {number} rate - The discount rate percentage
* #param {number} initialCost - The initial investment
* #param {array} cashFlows - An array of future payment amounts
* #return {number} The calculated Net Present Value
*/
function getNPV(rate, initialCost, cashFlows) {
return cashFlows.reduce(
(accumulator, currentValue, index) =>
accumulator + currentValue / Math.pow(rate / 100 + 1, index + 1),
initialCost
);
}
I've explained most of it on my blogpost.
Hope this helps :)
One big thing you are missing with this is the cost.
You have periods, you have rate, you have rate percent. But there is nothing there for the "cost".
You say you have this in Excel, and other languages. If you understand the calculations in Excel, then you may understand how you should do it in JavaScript.
In Excel you use the nifty function =NPV(.... where it takes 2 arguments. The first is the "RATE" and the second is the "VALUE" which can be multiple values. When you do this in Excel, one of the values you pass in would be the total cost. So you have something like this....
=NPV(2%,[total cost],[Year1Value],[Year2Value],[Year3Value],....) or =NPV(A1,A2:A12)
The "Total Cost" would go where you spend the money....assuming its at the end of Year 1, it would go before the "value" / return from year one.
With that being said, another thing to consider is determining WHEN the cost was needed.
If the cost is upfront, then it would be taken out of the "array" of values section and added to the NPV calculations such as....
=NPV(A1,A3:A12) + A2
Where cell A2 is the Cost (upfront) and A1 is the rate and A3-A12 are all the returns.
As a simple example, if you have the rate somewhere on the page, you can loop through the arguments that are going to be passed to it such as below....
function NPV() {
var args = [];
for (i = 0; i < arguments.length; i++) {
args = args.concat(arguments[i]);
}
var rate = document.getElementById("rate").value;
var value = 0;
// loop through each argument, and calculate the value
// based on the rate, and add it to the "value" variable
// creating a running total
for (var i = 1; i < args.length; i++) {
value = value + ((args[i])/(Math.pow(1 + rate, i)));
}
return value;
}
Additionally, you could also look for a library such as Finanace.JS http://financejs.org/
This worked for me
function getNPV(rate, a, payment) {
var npv = 0;
for (var i = 0; i < a.length; i++) {
npv += payment / Math.pow(1 + rate, a[i]);
console.log(payment / Math.pow(1 + rate, a[i]))
}
return npv;
}
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?
FIDDLE
https://jsfiddle.net/o1hq1apw/2/
The current BTC price is 2700$.
The price has increased by +34% in 7Days.
I hold 3.011 BTC, how can i calculate my profit?
currentPrice = 2700;
percent = 34;
holdings = 3.011;
alert( calcPec(currentPrice,percent,holdings) );
The current BTC price is 2700$.
The price has increased by -7% in 2Days.
I hold 3.011 BTC, how can i calculate my loss?
currentPrice = 2700;
percent = -7;
holdings = 3.011;
alert( calcPec(currentPrice,percent,holdings) );
// This is what i have but it is not correct
function calcPec(currentPrice,percent,holdings)
{
res = currentPrice*percent/2;
sum = holdings*res;
return '$'+sum;
}
So you hold 3.011 BTC which is currently 2700$ per BTC.
7 days ago the price of on BTC was equal to 100%, now it has risen by 34% so the 2700$ equal 134%.
To calculate the price from 7 days ago you have to divide 2700 by 134%, which is approx. 2014$.
So your earnings are (2700 - 2014) * 3.011 = 2065
Your code should be the following:
function calcPec(currentPrice, percent, holdings)
{
oldPrice = currentPrice / ((100 + percent) / 100);
sum = (currentPrice - oldPrice) * holdings;
}
You forgot to divide the percentage by 100 to get a fraction.
// The current BTC price is 2700$.
// The price has increased by +34% in 7Days.
// I hold 3.011 BTC, how can i calculate my profit?
currentPrice = 2700;
percent = 34;
holdings = 3.011;
console.log(calcPec(currentPrice, percent, holdings));
// The current BTC price is 2700$.
// The price has increased by -7% in 2Days.
// I hold 3.011 BTC, how can i calculate my loss?
currentPrice = 2700;
percent = -7;
holdings = 3.011;
console.log(calcPec(currentPrice, percent, holdings));
function calcPec(currentPrice, percent, holdings) {
const curr = holdings * currentPrice;
const changed = curr * (1 + (percent / 100));
return '$' + (changed - curr);
}
In future you probably want to define your percentage as a fraction to begin with, to avoid errors like this. So instead of percent = 34 you'd do percent = 0.34
EDIT fixed other errors too;
You could divide the percent value by 100 to the the fraction of the change.
function calcPec(price, percent, holdings) {
return '$' + (holdings * price * percent / 100).toFixed(2);
}
console.log(calcPec(2700, 34, 3.011));
console.log(calcPec(2700, -7, 3.011));
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.