Calculate loss and profit from percentage - javascript

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

Related

Jquery Adding tax to price with commas

I am having trouble calculating with commas in my price what would be de best solution to solve this?
I am console log the right price and want to get the tax.
example console log: "€1.652,89"
$(document).ajaxSuccess(function() {
var price = $('.yith_wcp_group_final_total').text();
console.log(price);
var tax = 21
var total = (price * tax) / 100;
$('#B_subtotal').html(total);
console.log(total);
});
//EDIT
$(document).ajaxSuccess(function() {
var price = $('.yith_wcp_group_final_total').text();
price = Number(price.replace(/[^0-9\.-]+/g,""));
console.log(price)
var tax = 21
var total = price * (100 + tax) / 100;
var roundup = total.toFixed(2);
$('#B_subtotal').html(roundup);
console.log(total);
console.log(roundup);
});
So i get 1.900,83
and after the calculation i get 2.3000043
How could I get the comma and dots back on the right place?
You are getting values in a string. Just convert the string into a float as we have a decimal point and apply regex as we have a currency sign in it. Regex will check the value and we will get the value in float which can be used with tax multiplication.
var price = $('.yith_wcp_group_final_total').text();
price = Number(price.replace(/[^0-9\.-]+/g,""));
console.log(price)
var tax = 21
var total = (price * tax) / 100;
$('#B_subtotal').html(total);
total = price + total
console.log(total.toLocaleString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
First you need to convert "€1.652,89" from "currency" to float. In this example I used the parseLocaleNumber function (https://stackoverflow.com/a/29273131/5334486).
This gives you float 1652.89 which can be correctly used to compute taxes and total.
You can then format total back to currency using Intl.NumberFormat() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
let price = "€1.652,89"
const taxPercent = 21
// REMOVE THE EURO SYMBOL FROM PRICE
price = price.substring(1)
// CONVERT LOCALIZED NUMBER TO FLOAT
const priceAsNumber = parseLocaleNumber(price, 'nl')
console.log(priceAsNumber) // 1652.89
// GET TAXES
const taxAmount = priceAsNumber * taxPercent / 100
console.log(taxAmount) // 347.1069
// GET TOTAL
const total = priceAsNumber + taxAmount
console.log(total) // 1999.9969
// FORMAT TOTAL TO CURRENCY
const totalRounded = new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR' }).format(total)
console.log(totalRounded) // "€ 2.000,00"
//
// HELPER FUNCTION
//
// https://stackoverflow.com/a/29273131/5334486
//
function parseLocaleNumber(stringNumber, locale) {
var thousandSeparator = Intl.NumberFormat(locale).format(11111).replace(/\p{Number}/gu, '');
var decimalSeparator = Intl.NumberFormat(locale).format(1.1).replace(/\p{Number}/gu, '');
return parseFloat(stringNumber
.replace(new RegExp('\\' + thousandSeparator, 'g'), '')
.replace(new RegExp('\\' + decimalSeparator), '.')
);
}

Ternary Operator not yielding expected result

In JavaScript: I have a ternary operator being instructed to return a tip percentage of %15 if the bill amount is between $50-300, otherwise being instructed to reuturn a tip percentage of %20. On a bill amount of $275, it is still yielding %20. I have looked at many examples of functioning ternary operators and my code seems to be properly worded and yet the result comes out incorrect every time. In what way am I failing?
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
let bill;
let tip_percentage = bill >= 50 && bill <= 300 ? 0.15 : 0.2;
bill = bill_1;
console.log(`The first table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
bill = bill_2;
console.log(`The second table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
bill = bill_3;
console.log(`The third table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
This is the result being given:
As #Matt said in the comment, tip_percentage is not a function and must be calculated each time you change the bill amount.
Try this:
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
function getTip(bill) {
var tip = (bill >= 50 && bill <= 300) ? 0.15 : 0.2;
return tip;
}
alert(`Bill one's tip: ${getTip(bill_1)}`);
alert(`Bill two's tip: ${getTip(bill_2)}`);
alert(`Bill two's tip: ${getTip(bill_3)}`);
tip_percentage is already calculated.
If you want to make different result values depending on the variable, make them in the form of functions.
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
const tip_percentage = (bill) => (bill >= 50 && bill <= 300 ? 0.15 : 0.2);
const printTipResult = (bill) => {
console.log(`The third table's bill came out to $${bill}.
After the tip of ${tip_percentage(bill)}%
(equalling: $${bill * tip_percentage(bill)}) was added,
the final amount owed is: $${bill * tip_percentage(bill) + bill}`);
};
printTipResult(bill_1);
printTipResult(bill_2);
printTipResult(bill_3);

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.

How to calculate tax percentage in jQuery?

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

How do I get cart checkout price exact to the penny using Javascript?

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

Categories